简体   繁体   中英

why I am not getting updated props value in react

could you please tell me why not getting updated props value in react.

here is my code https://stackblitz.com/edit/react-redux-basic-counter-1e8gdh?file=shared/components/NavBar.js

In my example I have a button - .on click it decrement the value. I dispatch the action value is decremented but I am not getting updated value

 handle=()=>{
    this.props.decrement();
    this.getCount();
  }

  getCount=()=>{
    const {counter}= this.props;
    console.log(counter);
  }

see my console.log

expected output is -1

current output is 0

why? It is showing output when I click on - button

The reason is at the point of printing the value in the console the props are not updated. When the props are updated the react component re-renders and display the counter value. To check that you can use a setTimeout .

  handle=()=>{
    this.props.decrement();
    setTimeout(this.getCount,10)
  }

if you want to console log the value you can you the life cycle. you can use componentDidUpdate

   componentDidUpdate(prevProps) {
    if (this.props.counter !== prevProps.counter) {
      console.log(this.props.counter);
    }
  }

or componentWillReceiveProps (for react version < 16)

  componentWillReceiveProps(newProps) {
  if( newProps.counter != this.props.counter ) {
    console.log(newProps.counter);
  }
}

or else getDerivedStateFromProps (react version 16 +)

  static getDerivedStateFromProps(nextProps, prevState) {
  if(nextProps.counter !== prevState.counter ) {
     console.log(nextProps.counter);
  }
}

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