简体   繁体   中英

React: how to force state changes to take place after setState

How to force the state update to take place in React after calling setState?

As far as I know, state is effectively updated when render is called next time. Also, forceUpdate() should re-render the component and update the state changes immediately, right? However this doesn't seem to be the case. Here's an example.

handleSomeEvent(data) {
    this.setState({
        data: data
    })
    this.forceUpdate()

    // At this point state should be updated but it isn't
    this.props.consumeData(this.state.data) // consumeData will receive old data
}

How do I ensure state is actually updated before calling consumeData?

setState() is asynchronous, so you can do it in the callback:

handleSomeEvent(data) {
  this.setState({
    data: data
  }, () => this.props.consumeData(this.state.data)); // using `data` would work as well...
}

Regarding access to the state that just changed, @Samuli Hakoniemi's answer is the preferred way in the docs (iirc).

I'd say the following code should also run the state change before the data handling:

handleSomeEvent(data) {
    const _handleDataChange = async () => {
    this.props.consumeData(this.state.data) 
    }

    this.setState({data: data})
    _handleDataChange();
}

As _handleDataChange is an async call, it should be run after the (async) setState call.

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