javascript - 基于 redux 请求更改处理页面刷新的正确方法
问题描述
我创建了一个将请求 API 的 redux,如果结果是 200,我想使用history
.
问题是:如果操作成功,我不知道如何触发此更改。
我可以在我的 useCase 函数中重定向用户,但我不能使用history.push
pathName/state 参数,因为它只适用于 React 组件。
所以这就是我在我的 React 组件中所做的:
const acceptProposalHandler = () => {
store.dispatch(acceptProposal(id)).then(() => {
setTimeout(() => {
if (isAccepted) { //isAccepted is false by default but is changed to true if the
//request is 200
history.push({
pathname: urls.proposal,
state: {
starterTab: formatMessage({id: 'proposalList.tabs.negotiation'}),
},
});
}
}, 3000);
});
};
有时它可以工作,但有时它不会。出于某种原因,.then
即使请求失败也会调用。
我正在使用setTimeOut
,因为如果我不这样做,它将跳过 if 语句,因为 redux 尚未更新状态isAccepted
。
这是我来自 redux 的 useCase 函数:
export const acceptProposal = (id: string) => async (
dispatch: Dispatch<any>,
getState: () => RootState,
) => {
const {auth} = getState();
const data = {
proposalId: id,
};
dispatch(actions.acceptProposal());
try {
await API.put(`/propostas/change-proposal-status/`, data, {
headers: {
version: 'v1',
'Content-Type': 'application/json',
},
});
dispatch(actions.acceptProposalSuccess());
} catch (error) {
dispatch(actions.acceptProposalFailed(error));
}
};
我做错了什么?我正在使用带有 thunk 的 Redux,但我不熟悉它。
解决方案
“.then 即使请求失败也会被调用。” <- 这是因为acceptProposal
捕获 API 错误而不是重新抛出它。如果异步函数没有抛出错误,它将解决(即调用.then
)。它可以重新抛出错误,因此调用者会看到错误:
export const acceptProposal = (id: string) => async (
// ... other code hidden
} catch (error) {
dispatch(actions.acceptProposalFailed(error));
// ADD: re-throw the error so the caller can use `.catch` or `try/catch`
throw error;
}
};