做出反应 - 在render()之前从存储中获取状态

时间:2017-11-20 23:31:51

标签: javascript reactjs react-native promise

我正在使用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中使用承诺如下:

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

永远不会到达指定的行。 (在checkIfTermsAgreedTo中,在“then”下)。 发生了什么事?

1 个答案:

答案 0 :(得分:1)

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

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

的最佳指南之一