javascript - React Native Fetch 函数清除状态
问题描述
每个人我都是 React Native 的新手,正在尝试一些可能超出我想象的东西。我希望使用 fetch 命令来提取数据并将其保存为我的状态的属性。这是我的代码:
componentDidMount() {
fetch('http://swapi.co/api/people/')
.then(response => response.json())
.then(responseData => {
this.setState({
tweets: responseData.results
});
console.log(this.state.tweets)
})
.catch(error => {
alert('Fetching and parsing data error ' + error);
})
.then(console.log(this.state.tweets));
第一个 console.log() 输出我要拉的正确数组,但第二个 console.log() 显示 null。
有人可以解释为什么会这样吗?谢谢
解决方案
setState
是异步的,因此在设置后立即检查状态将不起作用。
要在设置后查看状态 - 将回调传递给设置状态作为第二个参数。
this.setState({
tweets: responseData.results
}, () => console.log(this.state.tweets));
setState
还调用render
方法,因此您可以在那里预览新状态。
推荐阅读
- javascript - 内部带有数组循环的数组过滤器
- javascript - 禁用图表的网格线居中
- javascript - div 上的下拉子菜单
- angular - 单元测试返回期望值的方法
- jdbc - 如何从 JDBC 记录集中删除一行(具有关系 extlib 的 XPage)
- sql-server - 数据库上线时运行存储过程
- react-native - 如何在 React Native 中创建标签导航栏?
- javascript - 带有codeigniter的ajax上的csrf令牌
- python - TypeError:无法将列表连接到字节 Python Telnet 错误
- java - 如果 csv 文件不存在,如何返回变量结果