我正在使用 React Native 和 Redux 制作一个应用程序,在我的一个屏幕上有一个状态变量,我从 componentDidMount()
上的商店中检索该变量,然后立即将其保存在屏幕的局部状态变量。所以我的 componentDidMount()
和 componentDidUpdate()
方法看起来像这样:
componentDidMount() {
this.props.getA(); // this sets this.props.A
}
componentDidUpdate(prevProps) {
if (!prevProps.A && this.props.A){
this.setState({
A: this.props.A
})
}
}
问题:
如果我离开此屏幕然后返回,this.props.A
仍然存在,但 this.state.A
不存在。我明白为什么会发生这种情况,但我想知道每次我像这样导航回屏幕时重新设置 this.state.A
的最佳做法是什么。
我的问题:
当屏幕挂载时,componentDidMount()
被触发。当您导航回已安装的组件时是否会触发某些事件?我知道我可以通过创建另一个状态变量来做到这一点,我可以在导航时自动切换该状态变量,或者可以调用 forceUpdate()
或其他东西,但我想要尽可能干净的解决方案。有什么想法吗?
谢谢!
最佳答案
以上声明方式不可取。
Initializing State from Props In most cases, this is an antipattern. Don’t “copy props into state.” It creates a second source of truth for your data, which usually leads to bugs. One source of truth is best.
Components will already re-render when their props change, so there’s no need to duplicate the props as state and then try to keep it up to date.
请点击此链接 https://daveceddia.com/where-initialize-state-react/ .
当您导航回已安装的组件时,您可以直接使用 props。
关于javascript - 当您导航回到它时更新已安装的屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56244361/