【问题标题】:State Returning Undefined --React Native状态返回未定义——React Native
【发布时间】:2017-12-11 05:33:08
【问题描述】:

我正在尝试从异步存储中获取值并将其分配给状态。 访问 URL 时,状态值变为空/未定义

 constructor(props) {
    super(props);
    this.state = {
        stAccntList: [],
        stUserAccountNo: '',
        stCustNo: '',
        resp: '',
    };
    AsyncStorage.getItem('UserAccountNo').then((value) => {
        if (value != '') {
            accno = value;
            this.setState({ stUserAccountNo: value });
           // alert(this.state.stUserAccountNo);
        }
    }).done();
    AsyncStorage.getItem('CustomerNo').then((value) => {

        if (value != '') {
            cusno = value;
            this.setState({ stCustNo: value });
           // alert(this.state.stUserAccountNo);

        }
    }).done();


}


     componentWillMount() {

        let restUrl = urls.URL + this.state.stCustNo + "/" + "accounts" + "/" + this.state.stUserAccountNo;

}

this.state.CustNo 和 this.state.stUserAccountNo 返回 null 。

请告诉我哪里出了问题。

【问题讨论】:

  • 由于您尝试异步获取数据并更新状态,因此不能保证在 componentWillMount 执行之前数据可用。
  • 如何实现?
  • 取决于在componentWillMount中restUrl的目的是什么
  • 我会用那个 restUrl 打 API

标签: javascript reactjs react-native ecmascript-6


【解决方案1】:

由于您尝试异步获取数据并更新状态,因此不能保证在 componentWillMount 执行之前数据可用。

您可以在 componentDidMount 中使用 async-await 代替

constructor(props) {
    super(props);
    this.state = {
        stAccntList: [],
        stUserAccountNo: '',
        stCustNo: '',
        resp: '',
    };

}

async componentDidMount() {
   var userAccountNo = await AsyncStorage.getItem('UserAccountNo');
   var CustomerNo = await AsyncStorage.getItem('CustomerNo');
   if (userAccountNo != '') {
        this.setState({ stUserAccountNo: userAccountNo });
   }
   if (CustomerNo != '') {
        this.setState({ stCustNo: CustomerNo });
   }
   if(userAccountNo !== '' && CustomerNo !== '') {
     var restUrl = urls.URL + this.state.stCustNo + "/" + "accounts" + "/" + this.state.stUserAccountNo;
   }
}

【讨论】:

    【解决方案2】:

    restURL 是立即使用还是稍后使用(即点击事件或稍后的其他事件)?如果立即使用它,您可能希望使用promisesasync await 来跟踪AsyncStorage 在使用restURL 之前何时完成。如果您稍后使用该 URL,那么您可以简单地依赖它在您需要使用它之前完成,或者在使用前检查它。

    【讨论】:

    • 我将在componentWillMount中的restUrl下面立即使用
    • 然后查看 Promise 和异步等待。您必须知道两个 AsyncStorage 都已完成(触发了它们的 then())才能知道您已恢复数据。
    猜你喜欢
    • 1970-01-01
    • 2018-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-01
    • 2018-09-25
    • 1970-01-01
    • 2018-12-31
    相关资源
    最近更新 更多