简体   繁体   中英

react child props does not update when sending updated parent state

i have a chart component and i'm fetching data from an api through the props data to put in chart but when i'm sending the parent to chart component as props it's not updating the parent state is updated but the child props are not updating and if i log it in

componentWillReceiveProps(props) {
  console.log(props);
  // it shows updated value but if i do this 
  this.loadData();
}

loadData = () => {
  console.log(props)
  // it's value is old and not updated 
}

i have check it in parent the state is updated is and i have a click event in parent when i first click it the parent state changes but chart component props will not change and if i click second time chart component props will the state of first time click state

here's my github repo https://github.com/naveenkash/forex look in chart component props and pages index.js chart in getting props through index.js

because in componentWillReceiveProps props is reference to new props, they are not yet available in other parts of class, so you should pass them to loadData

componentWillReceiveProps(props){
   this.loadData(props);
}

loadData=(props)=>{
   console.log(props)
}

What Dmitry said is accurate, this.props hasn't changed as of componentWillReceiveProps(props) . Therefore when you call this.loadData() you're still calling it with the old props.

Note that componentWillReceiveProps(props) is unsafe

You should use componentDidUpdate(previousProps) , where you can call this.loadData() and it will execute with updated this.props .

It's js scope issue not react event lift cycle issue, considering changing the code as below:

componentWillReceiveProps(props) {
  console.log(props);
  // it shows updated value but if i do this 
  this.loadData(props);
}

loadData = (newProps) => {
  console.log(newProps)
  // it's value is old and not updated 
}

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