简体   繁体   中英

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. How can this be possible? The log for the items array is run right before state is set.

This is preventing me from updating my state.

this.setState() does not run synchronously. 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.

Discussion about this topic here: https://github.com/facebook/react/issues/11527#issuecomment-360199710

Since setState works in an asynchronous way. That means after calling setState the this.state is not immediately changed. So if you want to perform an action immediately after setting state, use 2nd argument as callback on setState . Consider this example:

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

this.setState is rendering asynchronously. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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