reactjs – Redux componentDidUpdate获取以前的状态

我将Redux重构为我的代码,但无法弄清楚如何获得以前的状态.
我需要这个状态用于我的componentDidUpdate生命周期方法,以便我可以调用其他方法而不会陷入无限循环.

// when component re-renders
componentDidUpdate(prevState) {
 // if the current page changes, or the search term changes.
 if(prevState.currentPage !== this.props.bucketlistState.currentPage || 
  prevState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists();
 }
}
最佳答案
prevState是componentDidUpdate的第二个参数,第一个参数是prevProps

// when component re-renders
componentDidUpdate(prevProps, prevState) {
 // if the current page changes, or the search term changes.
 if(prevState.currentPage !== this.props.bucketlistState.currentPage || 
  prevState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists();
 }
}

检查documentation

句法:

componentDidUpdate(prevProps, prevState)

PS:它是一个反模式,具有可直接从道具派生的状态.您应该直接使用props并在componentDidUpdate中比较它们

// when component re-renders
componentDidUpdate(prevProps, prevState) {
 // if the current page changes, or the search term changes.
 if(prevProps.bucketlistState.currentPage !== this.props.bucketlistState.currentPage || 
  prevProps.bucketlistState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists();
 }
}

并且因为你只使用道具进行比较,所以在React的v16.3之前更合适的地方就是componentWillReceiveProps函数,但是这个函数很可能会在未来的主要React版本中删除,并且它有望用于你使用componentDidUpdate.有关更多信息,请检查

Can getDerivedStateFromProps be used as an alternative to componentWillReceiveProps

// when component re-renders
componentWillReceiveProps(nextProps, nextState) {
 // if the current page changes, or the search term changes.
 if(nextProps.bucketlistState.currentPage !== this.props.bucketlistState.currentPage || 
  nextProps.bucketlistState.searchTerm !== this.props.bucketlistState.searchTerm) {
  this.getBucketlists(nextProps);
 }
}

转载注明原文:reactjs – Redux componentDidUpdate获取以前的状态 - 代码日志