gpt4 book ai didi

reactjs - Redux componentDidUpdate 获取之前的状态

转载 作者:行者123 更新时间:2023-12-03 13:28:54 24 4
gpt4 key购买 nike

我将 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();
}
}

最佳答案

prevStatecomponentDidUpdate的第二个参数,第一个参数是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 导出的状态是一种反模式。您应该直接使用 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();
}
}

由于您仅使用 props 进行比较,因此在 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 获取之前的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48538342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com