我正在使用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 Promise
和resolve
初始化reject
时,请记住resolve
和reject
只是您在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/