【问题标题】:React Native get initial state from async componentDidMountReact Native 从异步 componentDidMount 获取初始状态
【发布时间】:2016-08-28 10:21:32
【问题描述】:

我想从已经从 componenDidMount 调用的异步函数中向 render() 显示状态值,但在第一个执行组件中它返回未定义,第二次尝试显示正确的数据

这是我的状态this.state.userData

我的问题是,render() 和 componentDidMount() 之间的优先处理函数是什么?

这是我的代码

componentDidMount: function(){
    store.get('userData').then((val) => {
        if(typeof val != 'undefined'){
            this.setState({'userData':val});
        }
    }).done();
},
render: function() {
    return(
        <View>
              <Text>{this.state.userData}</Text> // displaying undefined
        </View>
    );
}

【问题讨论】:

  • 似乎代码按预期工作。使用 promise 对象不会阻塞主线程(这就是 promise obj 的用途)。在调用 store.get(..) 调用渲染函数并查找 userData 但它在第一次渲染中不存在,因为 setState({'userData':val}) 没有工作并导致第二次渲染。如果您在 getInıtıalState() 中使用 '' 空字符串添加此状态,您将不会看到未定义。您正在尝试解决 undefined in componentdid mount 但没有任何问题。

标签: javascript android reactjs react-native


【解决方案1】:

我不确定你在问什么。

据我了解:您想在调用 render() 之前执行一个函数来设置数据。 在这种情况下:查看生命周期方法 -> link。它很好地解释了您可以在调用 render 之前使用 componentWillMount() 。

但是:这并不能保证您在调用 render 之前拥有数据。我建议您设置一个额外的状态变量以了解异步调用何时完成,然后在此之前调用加载微调器。

类似:

constructor(props){
 super(props);
 this.state={
  loading: true
 }
}

在你的函数中:

this.setState({userData:val, loading: false});

渲染:

render() {
if(this.state.loading){
  return( <ActivityIndicator size='large' style={{height:80}} />
}
else{
 return(
     <View>
           <Text>{this.state.userData}</Text> // displaying undefined
     </View>
 );
}

(应该只给出一个想法 - 代码是即兴创作的......但应该解决未定义的问题) 玩得开心

【讨论】:

  • 感谢您的信息我将 componentDidMount 更新为 componentWillMount 但在我的情况下,我需要等待结果,因为我使用 promises 函数来获取值,并且它在第一次尝试组件时导致结果未定义
  • 那么为什么不将渲染转移到不同的地方,直到你得到“存储”的结果?在那种情况下,你肯定不会得到 undefined
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 2016-09-22
  • 2021-12-01
  • 2019-08-20
  • 1970-01-01
  • 2021-07-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多