React Native-渲染()之前从存储中获取状态



我正在使用 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中,在"然后"下)。发生了什么?

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

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;
    })
}       

当您使用resolve初始化new Promisereject时,请记住,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/promiss/promises#whats-whats-promiss#whats-all-thats-fuss-fuss-about-about-p./p>

相关内容

  • 没有找到相关文章

最新更新