我正在使用react-native-simple-store,试图从存储中读取值。

constructor中定义了这个:

this.checkIfTermsAgreedTo = this.checkIfTermsAgreedTo.bind(this);


使用此功能

checkIfTermsAgreedTo(){
    return new Promise((resolve,reject) => {
      return store.get('agreed');
    })
    .then(agreed =>{
      console.log(agreed); --> This line is never reached
      console.log((agreed.terms == "YES") ? "AGREED!" : "Not agreed....");
      return agreed;
    })
  }


componentWillMount中使用Promise,如下所示:

componentWillMount(){
    this.checkIfTermsAgreedTo().then(agreed=>{
      this.setState({agreed:(agreed.terms == "YES")});
    })
      .catch(()=>{
        console.log("CATCH: Agreed, probably not found");
        this.setState({agreed:{terms:"NO"}})}
      );
  }


永远不会到达指定的行。 (在checktheTermsAgreedTo中的“ then”下)。
到底是怎么回事?

最佳答案

只需在第一个承诺中解决您的输出。

checkIfTermsAgreedTo(){
    return new Promise((resolve,reject) => {
      resolve(store.get('agreed'));
    })
    .then(agreed =>{
      console.log(agreed); --> This line is never reached
      console.log((agreed.terms == "YES") ? "AGREED!" : "Not agreed....");
      return agreed;
    })
}


当使用new Promiseresolve初始化reject时,请记住resolvereject只是您在then中传递的功能块。例如。



var i = 100;

var k = new Promise((resolve, reject) => {
	if(i === 100)
		resolve("I AM RESOLVED BY YOUR FIRST FUNCTION BLOCK")
	else
		reject("I AM REJECTED BY YOUR SECOND FUNCTION BLOCK")
})

// Now when you resolve the promise like below, the `thenable` struct
// will expect two function blocks or atleast one which are the
// success(resolve) and error(reject) blocks

resolveBlock = (response) => {
	console.log(response);
}

rejectBlock = (reject) => {
	console.log(reject);
}

k.then(resolveBlock, rejectBlock);

// I AM RESOLVED BY YOUR FIRST FUNCTION BLOCK

// OR IT CAN BE WRITTEN AS BELOW WHICH IS THE USUAL NORM
// k.then((response) => {
// 	console.log(response);
// }, (reject) => {
// 	console.log(reject);
// })





这是开始/修订Promises https://developers.google.com/web/fundamentals/primers/promises#whats-all-the-fuss-about的最佳指南之一

关于javascript - react native -在render()之前从存储获取状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47402861/

10-09 21:29