更新时间:2022-12-08 15:22:42
为了回答我自己的问题,我能够像这样重写它 (/src/controllers/data-controller/data-controller.js
,为了更清晰,添加了完整的代码):
To answer my own question, I was able to rewrite it like this (/src/controllers/data-controller/data-controller.js
, added the full code for better clarity):
import React from 'react';
import Papa from 'papaparse';
import {withRouter} from 'react-router-dom';
class DataController extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
this.getData = this.getData.bind(this);
}
componentWillMount() {
this.getCsvData();
}
fetchCsv() {
return fetch('/data/data.csv').then(function (response) {
let reader = response.body.getReader();
let decoder = new TextDecoder('utf-8');
return reader.read().then(function (result) {
return decoder.decode(result.value);
});
});
}
getData(result) {
this.setState({data: result.data});
}
async getCsvData() {
let csvData = await this.fetchCsv();
Papa.parse(csvData, {
complete: this.getData
});
}
render() {
return (
<section className="data-controller">
...
</section>
);
}
}
export default withRouter(DataController);
在这里,我使用内置的 fetch 来获取流,然后使用内置的流读取器读取流,并使用 TextDecoder
解码数据.我也不得不移动文件.之前它位于 /src/controllers/data-controller
但我不得不将它移动到 /public/data
.
Here I use the built in fetch to get it like a stream and then read the stream using the build in stream reader, and decode the data using TextDecoder
. I had to move the file also. Before it was located in /src/controllers/data-controller
but I had to move it to /public/data
.