react-native 項目中使用了 react-native-storagereact
storage.load({ key: 'loginState', }) .then(ret => { let params = { token: ret.token, userId: ret.userId, } }) .catch(error => { })
async componentDidMount() { let isLogin = await this.isLogin() if (isLogin) { // fetch username } else { // jump to login } } async isLogin() { try { let ret = await storage.load({ key: Common.loginState, }) return ret ? true : false } catch (error) { console.log('00') return false } }
componentDidMount() { let isLogin = this.isLogin() // 返回的是一個promise,promise裏封裝的有咱們返回的結果, 可是無法直接同步用 if (isLogin) { // fetch username } else { // jump to login } } async isLogin() { try { let ret = await storage.load({ key: Common.loginState, }) return ret ? true : false } catch (error) { console.log('00') return false } }
錯誤二react-native
componentDidMount() { let isLogin = this.isLogin() // 返回的永遠是3, 由於是異步,在進入 then, catch 以前,isLogin就調用完畢了,執行到 return 3結束 if (1) { // fetch username } else { // jump to login } } isLogin() { storage.load({ key: 'loginState', }) .then(ret => { return 1 }) .catch(error => { return 2 }) return 3 }