gpt4 book ai didi

javascript - React Native AsyncStorage 返回 promise 甚至使用 await 和 async

转载 作者:行者123 更新时间:2023-11-30 20:30:19 25 4
gpt4 key购买 nike

我研究了 AsyncStorage.getItem 中的问题。许多评论说我们应该在 AsyncStorage 上应用 awaitanync,例如

React Native AsyncStorage returns promise instead of value .

AsyncStorage.getItem returning promise

但是,它仍然像下面的快照一样向我返回 Promise。在这个 Promise 中,_55 包含正确的用户信息。每个人都会帮我找出问题并给我可能的解决方案吗?谢谢你!

快照: Debugger snapshot

reducer :

import {AsyncStorage} from "react-native";
import {LOGIN, LOGOUT, UPDATE} from './../actions/authActions'
import user from "./index";

export type State = {
user: Object,
login: boolean,
}

getUser = async (string) => { //Get user information form AsyncStorage
try {
return await AsyncStorage.getItem(string)
.then((user) => {
if (user !== null) {
return JSON.parse(user);
} else {
return null;
}
});
} catch (error) {
return null;
}
};

const initialState = {
info: getUser(),
login: !!this.info, // if not null, login = ture
};

function loginReducer(state: State = initialState, action) {
switch (action.type) {
case LOGIN:
return {
info: action.payload,
login: true,
};
case LOGOUT:
return {
info: null,
login: false,
};
case UPDATE:
return {...state, info: Object.assign(state.info, action.payload)};
default:
return state;
}
}

行动:

import {AsyncStorage} from "react-native";
import {requestLogIn, requestLogOut} from "../../config/api/authApi"

export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const UPDATE = "UPDATE";
export const ERROR = "ERROR";

export function login(user) {
return dispatch => {
return AsyncStorage.setItem("user", JSON.stringify(user)) //Store user information in AsyncStorage
.then(() => {
dispatch({
type: LOGIN,
payload: user
})
}).catch((error) => {
console.warn("Error: ", error);
dispatch({
type: ERROR,
payload: null
})
});
}
}

export function logout(token) { //
return dispatch => {
return requestLogOut(token).then((status) => {
if (status) {
return AsyncStorage.removeItem("user")
.then(() => {
dispatch({
type: LOGOUT,
})
}).catch(() => {
dispatch({
type: ERROR,
payload: null
});
});
} else {
dispatch({
type: ERROR,
payload: null
});
}
})

}
} ..// other actions

最佳答案

您的 getUser 是一个 async 函数,但您没有await它:

const initialState = {
info: getUser(), // <=== here
login: !!this.info,
};

async 函数返回 promise 。

在不深入了解代码的更广泛上下文的情况下,您可能想做这样的事情:

const initialState = {
info: null,
login: !!this.info,
};
getUser().then(info => initialState.info = info);

或者类似的东西。请注意,这意味着 initialState.info 将是 null,直到存储返回该值。如果您有更多需要该值的初始化,则必须从上面的 then 处理程序触发它。

(没有 catch 因为你已经定义了 getUser 它不能拒绝。)

关于javascript - React Native AsyncStorage 返回 promise 甚至使用 await 和 async,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50408050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com