简体   繁体   中英

state value is not modified after setState in react

I know setState is an async action so I have made a sync call to make sure that state value is updated before my componentWillReceiveProps triggers but still it shows me previous value. this code has written in my child element. I suspect is that any thing to do in my parent element?or is there any other reason? below is my code

constructor(props) {
    super(props);
    this.state = {

      loading: false,
      yearValue:Number(localStorage.getItem('year'))//this is 2019

    };
  }
  componentDidMount() {

  }
  componentWillReceiveProps(nextProps) {
    console.log(
      'before if condition...',
      nextProps,
      Number(localStorage.getItem('year'))
    );
    if (
      this.state.yearValue ===
      Number(localStorage.getItem('year')) //this condition satisfied twice before it changed the value
    ) {
      console.log('inside if condition.....', nextProps);
      this.setSstate = {

        loading: false
      };
    } else this.setState({ loading: false });
  }
  updatePrograValues = year => {//year = 2017
    if (year === Number(localStorage.getItem('year'))) {
      this.props.showPlanYearValues(year);
    } else {


      this.setState({

        loading: true
      },this.props.tooltipRefresher());
    }
  };

If I assume the errant ; in your setState call is a typo in the question and isn't in the actual code, the problem is here:

this.setState({
  loading: true
},this.props.tooltipRefresher());

That calls this.props.tooltipRefresher() and then passes its return value into setState , exactly the way foo(bar()) calls bar and passes its return value into foo .

If you meant for it to be called after the state value is updated, remove the () from it so you're not calling it, you're passing it into setState so setState will call it when the state is set:

this.setState({
  loading: true
},this.props.tooltipRefresher);
// No () --------------------^

If it's sensitive to the value of this (eg, tooltipRefresher expects this to be this.props ), you may need bind :

this.setState({
  loading: true
},this.props.tooltipRefresher.bind(this.props));

...or an arrow function:

this.setState({
  loading: true
},() => this.props.tooltipRefresher());

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