React: setState does not make results just as expected(not working?)

前端 未结 2 1859
独厮守ぢ
独厮守ぢ 2021-01-24 05:13

My project is Cordova + React(es6). I have a few problem with using the setState().

the data that is passed to state is not empty. But, passing the data to state, I rece

相关标签:
2条回答
  • 2021-01-24 05:46

    React setState() is an async operation so it does not deliver the result immediately after it is called in you code. You can access the updated state you if add console.log(this.state.data_source); inside your render() method which is only called when this.setState() completes.

    Have a looke a the React docs: https://facebook.github.io/react/docs/component-api.html#setstate

    setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.

    setState() will always trigger a re-render unless conditional rendering logic is implemented in shouldComponentUpdate().

    0 讨论(0)
  • 2021-01-24 05:48

    In addition to Piotr'a answer, setState can be passed a callback which is called with the new state, e.g.;

      this.setState({data_source: final_cash_data}, function(newState){
        console.log(newState.data_source)
      });
    
    0 讨论(0)
提交回复
热议问题