简体   繁体   English

React Native:更新状态的奇怪问题

[英]React Native: Strange Issue With Updating State

I am using the code below: 我正在使用以下代码:

makeRemoteRequest = () => {
    let items = []; 
    models.forEach(element => {  //models is an array of the list of models
        this.pushReports(element, items); 
    });
    console.log("This is the item array: ",items); 
    this.setState({
        data:items
    });
    console.log("This is the data in state: ",this.state.data); 
}

Somehow, the console log for the items array is showing me the array that I need, but the console log for the this.state.data is empty. 不知何故,items数组的控制台日志向我显示了我需要的数组,但是this.state.data的控制台日志为空。 How can this be possible? 这怎么可能? The log for the items array is run right before state is set. 在设置状态之前,将立即运行items数组的日志。

This is preventing me from updating my state. 这使我无法更新状态。

this.setState() does not run synchronously. this.setState()不同步运行。 Your state is not guaranteed to be updated on the next immediate line, but it will be updated properly on the next render cycle. 您的状态不能保证在下一个即时行上更新,但是会在下一个渲染周期正确更新。 Try putting console.log within render() and you'll see. 尝试将console.log放在render() ,您会看到。

Discussion about this topic here: https://github.com/facebook/react/issues/11527#issuecomment-360199710 关于此主题的讨论在这里: https : //github.com/facebook/react/issues/11527#issuecomment-360199710

Since setState works in an asynchronous way. 由于setState以异步方式工作。 That means after calling setState the this.state is not immediately changed. 这意味着在调用setStatethis.state不会立即更改。 So if you want to perform an action immediately after setting state, use 2nd argument as callback on setState . 因此,如果要在设置状态后立即执行操作,请使用第二个参数作为setState回调。 Consider this example: 考虑以下示例:

this.setState({
    data: newData
}, () => {
  //TODO: Do something with this.state here
});

this.setState is rendering asynchronously. this.setState异步呈现。 And you're trying to print in next line so it will not give immediate results as you want. 而且您正在尝试在下一行中打印,这样它就不会立即产生想要的结果。

Solution: do this in next line, 解决方案:在下一行中执行此操作,

setTimeout(() => {console.log("This is the data in state: ",this.state.data) }, 1000)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM