首页 > 解决方案 > 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。

有人可以解释为什么会这样吗?谢谢

标签: javascriptapireact-nativefetch

解决方案


setState是异步的,因此在设置后立即检查状态将不起作用。

要在设置后查看状态 - 将回调传递给设置状态作为第二个参数。

this.setState({
    tweets: responseData.results
}, () => console.log(this.state.tweets));

setState还调用render方法,因此您可以在那里预览新状态。


推荐阅读