如何在redux中调用getState()之前等待数据加载



我有一个动作,userAction,它将调用API从数据库中加载数据,我想在单独的动作calcAction中使用该数据,这样我就可以用userAction的数据发布到API,但是当我在calcAction中调用getState()时,我得到了初始状态。我如何确保getState()只在userAction从数据库加载数据后才能获得状态?

我的calcReducer是这样的:

export const getAllCharReq = () => (dispatch, getState) => {
const { userData } = getState();
axios.post('/api/character', userData).then((res) => {
dispatch({
type: GET_ALL_CHAR_REQ,
payload: res.data,
});
});
};

在app组件中调用userAction,以便它在第一次访问网站时加载用户数据。并且在子组件的componentDidMount()中调用calcAction,因此只有在访问组件时才能获得相关数据。所以,只有当用户先加载这个子组件时,才会出现问题。如果用户要导航到该子组件,则会加载userData

你可以在你的思维中处理它,只在userData存在时执行取回。

export const getAllCharReq = () => (dispatch, getState) => {
const { userData } = getState();
if (userData) {
axios.post("/api/character", userData).then((res) => {
dispatch({
type: GET_ALL_CHAR_REQ,
payload: res.data
});
});
} else {
dispatch({
type: "ERROR",
payload: "No user data found"
});
}
};

你也可以将userData作为参数从你的组件传递给动作创建者,这是我建议的,如果它与你的应用程序结构是可行的。在组件中,除非userData被加载,否则您将知道不要分派该任务。

export const getAllCharReq = (userData) => (dispatch) => {
axios.post("/api/character", userData).then((res) => {
dispatch({
type: GET_ALL_CHAR_REQ,
payload: res.data
});
});
};

最新更新