javascript - 当您导航回到它时更新已安装的屏幕

标签 javascript reactjs react-native redux react-redux

我正在使用 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/

相关文章:

javascript - Node JS mysql数据库断开连接

javascript - LinkedIn Javascript SDK 无法返回职位

javascript - 如何在 React Native 的 FlatList 顶部和底部(同时)使用 "Pull to refresh"?

android - 当 i18n.locale 更改时更改原生 android 上的启动图像

javascript - 在 Node.js/Express 中,我如何 "download"一个页面并获取它的 HTML?

javascript - 如何将变量作为全局参数传递给 IIFE 函数?

reactjs - react native 传奇 yield 调用不起作用

javascript - prop `store` 在react-redux Provider 中如何工作?

javascript - React Hooks 渲染两次

react-native - 在react-navigation TabNavigator中,如何设置Params