React native:即使在模拟器上重新加载后,State似乎仍保留以前的状态

React native: State seems to retain previous state even after reload on the simulator

本文关键字:State 保留 状态 加载 native 模拟器 新加载 React      更新时间:2023-09-26

我有一个代码可以做这样的事情:(伪代码)

class extends Component{
   constructor(){
       this.state={
         condition1 : false,
         condition2 : false,
         condition3 : false,
         condition4 : false,
       }
       //set all 4 condition states to true once data loading has completed from the store
   }

   render(){
      return(
        if (this.state.condition1 && this.state.condition2 && this.state.condition3 && this.state.condition4)
           Render Main component
        else
           Render loading screen
      );
}

}

基本上,我有4个状态,用于在加载主组件之前检查数据是否已加载。一旦Store(从另一个文件)完成加载数据,它就会发出一个事件,导致4个状态设置为true,从而加载主组件。然而,一旦我从Genymotion模拟器中点击重载按钮,这4种状态将保持为true,不会重置为false,导致应用程序加载主组件并崩溃。(由于数据还没有准备好)我已经尝试在ComponentWillMount方法中再次将所有4个状态重置为false,但在主应用程序尝试加载主组件之前,这些状态似乎没有及时重置为false。在生命周期的哪个组件中,我应该将状态重置为false?或者我应该忽略这个问题,因为在实际设备上重新加载应用程序是"不现实的"?

在生命周期的哪个组成部分中,我应该将状态重置为是否为false?

文档建议在渲染之前使用componentWillReceiveProps更新状态。我已经为我的项目做了这件事,而且效果很好,不过根据您的用例,您可能需要检查newPropsthis.props是否不同。

https://facebook.github.io/react/docs/component-specs.html

组件WillReceiveProps

在组件接收新道具时调用。此方法不是调用进行初始渲染。

利用这个机会对道具转换做出反应render()是通过使用this.setState()更新状态来调用的可以通过this.ops访问旧道具。调用this.setState()在该函数中不会触发额外的渲染。

我已经设法通过减少网络获取请求的数量来解决这个问题。似乎同时有多个网络请求会导致不稳定,尽管原因尚不清楚。