简体   繁体   中英

Using new lifecycle methods for fetching data by a changing id in React + Redux

I have done it like this in React <= 16.2 :

componentDidMount () {
  fetchData(this.props.id)
}

componentWillReceiveProps(nextProps) {
  if (this.props.id !== nextProps.id) {
    fetchData(nextProps.id)
  }
}

render() {
  if (this.props.isLoading) {
    return <Loader />
  } else {
    return <SuperComp this.props.data />
  }
}

The component was connected and fetchData was a redux-thunk action creator managing a simple state: { isLoading: ..., data } . We can add error handling and cancellation on subsequent requests, but that is out of scope for now.

The basis of this is that the component requested it's own data every time the id prop changed, but only once for every change of the id prop.

I have no idea how it is properly done in React 16.4, the getDerivedStateFromProps is a static synchronous something returning the new state.

There is a long comment on github by bvaughn but it directly stores the data in state and initiates the refetch when the data is null. But if I store my data in redux , I cannot just null out my data in getDerivedStateFromProps (or can I?).

Can someone explain how can I do the same in "modern" React ?

Why not to just use componentDidUpdate for that purposes (by the way examples from official documentation also suggest that).

componentDidUpdate(prevProps) {
  if (this.props.id !== prevProps.id) {
    fetchData(this.props.id);
  }
}

What about getDerivedStateFromProps - they also warn about more simple alternatives:

If you need to perform a side effect (for example, data fetching or an animation) in response to a change in props, use componentDidUpdate lifecycle instead.

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