【发布时间】:2021-03-11 14:41:57
【问题描述】:
我在反应中遇到了 redux thunk 的问题。在 thunk 文件中,我使用 dispatch action 并从 reducer 更改 isSuccess 和 isLoading 标志,但在组件中,在 API 调用之后,我得到这些的先前值而不是当前值。
components.jsx
await addClient(valueToSubmit, employee.tenantId).then((response) => {
if (isSuccess) {
showToast(toastTypes.SUCCESS, translate("client_add_success"));
resetForm();
setSubmitting(false);
toggleModal();
setFieldsWithError([]);
} else {
showToast(
toastTypes.ERROR,
message.debugMessage?.includes("exist")
? translate("client_exist_error")
: translate("client_add_error")
);
setFieldsWithError(message.payload);
}
});
thunk.js
export const addClient = (data, tenant) => async (dispatch) => {
const tenantId = tenant?.replace(/['"]+/g, "");
dispatch(requestAddClient());
return await api(
"post",
apiUrl,
data,
tenant ? { "tenant-uuid": tenantId } : {},
false
)
.then((response) => {
return dispatch(receiveAddClient(response.data.payload));
})
.catch((err) => {
return dispatch(errorAddClient(err.response));
});
};
actions.js
export const requestAddClient = () => {
return {
type: REQUEST_ADD_CLIENT,
};
};
export const receiveAddClient = (client) => {
return {
type: RECEIVE_ADD_CLIENT,
client: client,
};
};
export const errorAddClient = (message) => {
return {
type: ERROR_ADD_CLIENT,
message,
};
};
reducer.js
case REQUEST_ADD_CLIENT:
return {
...state,
client: {},
isSuccess: false,
isLoading: true,
};
case RECEIVE_ADD_CLIENT:
return {
...state,
client: action.client,
clients: [...state.clients, action.client],
isSuccess: true,
isLoading: false,
};
case ERROR_ADD_CLIENT:
return {
...state,
client: {},
message: action.message.data,
isSuccess: false,
isLoading: false,
};
我无法解决这个问题。如果有人知道原因,请告诉我。提前谢谢!
【问题讨论】:
标签: javascript reactjs redux state thunk