javascript - 在 react.js 中使用 promise 获取数据。状态为空。为什么?
问题描述
从 CSV 文件中获取数据时出现问题。这是我的代码:
constructor(props) {
super(props);
this.state = {
data: [],
isLoading: false,
};
console.log(this.state.data) // Data is gone =(
}
toCSV(response){
let reader = response.body.getReader();
let decoder = new TextDecoder('utf-8');
return reader.read().then(function (result) {
let data = decoder.decode(result.value);
let results = Papa.parse(data);
let rows = results.data;
return rows;
});
}
componentDidMount() {
this.setState({ isLoading: true });
let dataNames;
return fetch('url/someFile.csv')
.then(response => this.toCSV(response))
.then(data => console.log(data)) // Data is here
.then(data => this.setState(
{ data: data, isLoading: false }
));
}
fetch 内部的输出:
(3) […]
0: Array(4) [ "abc", " 1", "aha", … ]
1: Array(4) [ "def", "2", "test", … ]
2: Array(4) [ "ghi", "3", "something", … ]
length: 6
构造函数中的输出:
[]
length: 0
我不明白为什么this.state是空的。我知道 promise 是一个异步函数,但我认为this.setState({ data: data, isLoading: false })会将数据设置到this.state.data中,然后实现 promise。
我在这里找到了这个解决方案,但我无法解决这个问题:React: import csv file and parse
我也尝试用JSON 文件来做,因为我认为问题是我的toCSV 函数,但结果是一样的......
fetchJSON() {
fetch(`someJSONfile.json`)
.then(response => response.json())
.then(response => console.log(response))
.then(data =>
this.setState({
data: data,
isLoading: false,
})
)
.catch(error => console.log(error));
}
我希望你们中的一个人可能有一个想法。谢谢你的时间 :)
解决方案
你有一个额外.then
的没有这个数据。下面的代码应该适合你。
componentDidMount() {
this.setState({ isLoading: true });
let dataNames;
return fetch('url/someFile.csv')
.then(response => this.toCSV(response))
.then(data => {
console.log(data)
this.setState({ data: data, isLoading: false })
})
}
另外,console.log 不在合适的地方,如果你想记录一些东西来检查它,它应该放在 setState 执行之后。
推荐阅读
- laravel - Laravel 应用程序非常慢 - 启动超过 3 秒,加载超过 2 秒
- javascript - PHP 没有得到 Ajax 的发送值
- android - 调用 startActivityForResult 后是否会发生配置更改?
- swiftui - 在 SwiftUI 中传递 Lat/Long 函数
- javascript - Gatsby Image 查询返回乱序图像
- javascript - 如何从函数内部发送消息(Discord.js)
- python - 丢失的字母,基本转换
- powerbi - 何时在 Power BI 中使用计算字段与度量?
- javascript - 修复了导航栏在不在顶部且不滚动时消失的问题,无法按预期工作
- docker - 如何在 Docker 中通过端点创建不同的端口映射?