Redux componentDidUpdate获取以前的状态

ckw*_*aba 4 reactjs redux

我将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();
 }
}
Run Code Online (Sandbox Code Playgroud)

Shu*_*tri 8

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();
 }
}
Run Code Online (Sandbox Code Playgroud)

查看文档

句法:

componentDidUpdate(prevProps, prevState)
Run Code Online (Sandbox Code Playgroud)

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();
 }
}
Run Code Online (Sandbox Code Playgroud)

并且因为你只使用道具进行比较,所以在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);
 }
}
Run Code Online (Sandbox Code Playgroud)