【问题标题】:React Native Fetch Function Clearing StateReact Native Fetch 函数清除状态
【发布时间】:2019-01-01 17:51:31
【问题描述】:

每个人 我是 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。

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

【问题讨论】:

  • 您也可以在console.log 中添加一些字符串以查看首先调用的内容。前任。 console.log('after setting state', this.state.tweets)

标签: javascript api react-native fetch


【解决方案1】:

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

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

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

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

【讨论】:

    【解决方案2】:

    如果您将 console.log 标记为“first”、“second”等,您将看到最后一个 console.log 首先调用。所以解决了这个问题,你应该用胖箭头或匿名函数包装最后一个 console.log。所以它会按照你想要的顺序被调用。

    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)); // Here
    }
    

    【讨论】:

      猜你喜欢
      • 2018-03-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-12
      • 2015-09-06
      • 1970-01-01
      • 2018-12-25
      • 2017-12-28
      • 1970-01-01
      相关资源
      最近更新 更多