componentdidmount()中的反应本机状态问题

时间:2019-03-29 15:49:17

标签: react-native

我在componentDidMount()中调用this.setState({})时遇到问题。 如果我在comonentDidMount()中调用this.setState({}),则似乎没有更新状态,因为如果我调用函数从Firestore中获取数据,则状态为“”,而不是componentDidMount()中的集合1。 / p>

构造函数:

this.state = {
  userid: '',
  username: '',
  useremail: ''
}

componentDidMount:

AsyncStorage.getItem('@userProfileDocID', function (error, result){
  if (result != null) {
    this.setState({ userid: result }, () => {
      alert(this.state.userid);
    });
  }
}.bind(this));

fire.collection('User').doc(this.state.userid).get().then(function (doc) {
  if (doc.exists) {
    this.setState({
      username: doc.name,
      useremail: doc.email
    });
  }
}.bind(this));

渲染:

return (
    <SafeAreaView style={{ alignItems: 'center' }}>
      <View style={{
        borderRadius: 5,
        width: 350,
        height: 350,
        shadowColor: 'black',
        shadowOffset: {width: 0, height: 0},
        shadowOpacity: 0.1,
        shadowRadius: 1.5,
        backgroundColor: 'white',
        alignItems: 'center',
        padding: 20 
      }}>
        <Icon name="ios-contact" color={'#d0d0d0'} size={100} />
        <Text>UserID: {this.state.userid}</Text> {/* <-- This Works (gets updated) */}
        <Text>Username: {this.state.username}</Text>
        <Text>Email: {this.state.useremail}</Text>
      </View>
    </SafeAreaView>
)

2 个答案:

答案 0 :(得分:1)

AsyncStorage是一个异步函数,顾名思义,因此您必须等待响应,这就是为什么状态什么都没有,因为异步存储尚未完成。

    try {
      const value = await AsyncStorage.getItem('@userProfileDocID');
      this.setState({ userid: value})
    } catch (error) {
      // Error retrieving data
    }

老实说,您应该使用ComponentDidMount,它更安全,但这是我的看法

请参阅this以获取更多意见

在ComponentWillMount中调用setState很危险,因为在渲染时调用setState会有风险

答案 1 :(得分:0)

请不要将代码放入componentDidMount()中,而是尝试将其放入Constructor()或componentWillMount()中。

我建议将该代码放在Constructor()方法的末尾,因为在下一版本的React Native中将不推荐使用componentWillMount

相关问题