简体   繁体   中英

React - Rendered item is not updating after initial render. When props change, should select different data

Rendered a state that is not updating when props change.

 componentDidMount(){ var count = 0; var dist = 0; (this.props.data).map(item => { if(item.type === this.props.selectedType){ return( dist = dist + item.distance, count++ ) } }) this.setState({ avg: dist/count }) }

I have tried shouldComponentUpdate and componentWillReceiveProps

the state of this.state.avg has been initialised in constructor but when calling this state in render it renders once but doesnt update when prop of 'selectedType' is changed by a different component.

componentDidMount is only called once and is invoked immediately after a component is mounted. So it won't have any effect if your props change.

This should work. You can use the componentDidUpdate method. It will run after the updating has happened.

componentDidUpdate(prevProps, prevState) {
   if (prevProps.selectedType !== this.props.selectedType) {
     // do something
   }
}

Hope this helps!

componentDidMount calls only once, and doesn't react on any props changing

componentDidMount() is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request.

for reaction on some props changing you have to use componentDidUpdate

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Notes:

componentWillReceiveProps is deprecated. Please don't use it.

Read the React documentation . It's base thing for development of good website

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