2017-12-11 5 views
1

비동기 저장소에서 값을 가져 와서 State에 할당하려고합니다. this.state.CustNo 및 this.state.stUserAccountNo가 null 반환상태 반환되지 않음 - 기본 네이티브

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; 

} 

URL로 심어 액세스하는 동안 국가의 값은 정의되지 않은/널오고있다.

어디로 잘못 가고 있는지 알려주세요.

+1

async-await의 사용을 만들 수있는, 그것 componentWillMount이 실행되기 전에 데이터를 사용할 수 있는지 guranteed 없습니다. –

+0

어떻게 달성할까요? –

+1

restWrl의 목적이 componentWillMount에 무엇인가에 따라 달라집니다. –

답변

2

데이터를 비동기 적으로 가져오고 상태를 업데이트하려고하므로 구성 요소가 실행되기 전에 데이터를 사용할 수 있다고 보장하지 않습니다. 비동기 데이터를 가져 오기 위해 노력하고 상태를 업데이트되기 때문에

대신 componentDidMount에

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; 
    } 
} 
+0

나는 당신을 확인하고 업데이트 할 것입니다. –

0

restURL은 즉시 사용되거나 나중에 사용됩니다 (즉, 클릭 이벤트 또는 나중에 다른 이벤트)? 바로 사용하는 경우 또는 async await을 사용하여 restURL을 사용하기 전에 AsyncStorage이 완료되면 추적 할 수 있습니다. 나중에 URL을 사용하는 경우 URL을 사용하거나 사용하기 전에 확인해야하기 전에 URL에 의존 할 수 있습니다.

+0

바로 componentWillMount에서 restUrl 아래에서 사용합니다. –

+0

그런 다음 약속과 비동기를 기다립니다. 두 개의 AsyncStorage가 데이터를 가지고 있음을 알기 위해 두 개의 AsyncStorage가 완료되었다는 사실을 알아야합니다 ('then()'이 트리거 됨). –