React Native从异步componentDidMount获取初始状态

时间:2016-08-28 10:21:32

标签: javascript android reactjs react-native

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

这是我的州 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>
    );
}

1 个答案:

答案 0 :(得分:7)

我不确定你在问什么。

据我了解:您希望在调用render()之前执行一个函数来设置数据。 在这种情况下:看一下生命周期方法 - &gt; link。它很好地解释了在调用render之前可以使用componentWillMount()。 enter image description here

但是:这并不能保证在调用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>
 );
}

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