这里有一个表单当提交时,调用这个函数
const handleSubmit = (e) => {
e.preventDefault();
try {
dispatch(addCategory({ category, identifier, definition }));
} catch (err) {
console.log(err.message);
}
};
,这是我的addCategory
动作在一个单独的文件中的代码。
export const addCategory =
({ category, identifier, definition }) =>
async (dispatch) => {
try {
const { data } = await axios.post(
"http://localhost:5000/Admin/addCategory",
{ category, identifier, definition }
);
dispatch({ type: "ADD_CATEG", payload: data });
} catch (error) {
dispatch({
type: "GET_ERROR",
payload: error.response.data.errorMessage,
});
}
};
如您所见,我在后端有一个错误处理,当用户输入重复数据时它会触发。我得到这个错误的方式是通过这个:
const { error } = useSelector((state) => state.categories);
我想要的是,当我在handleSubmit
中调度我的动作后,它检查错误是否为空。我试图在handleSubmit
中的try-catch块之后调用一个函数,看起来像这样。我试着运行它,然后我输入了正确的数据输入,没有错误,它显示"没有错误",但如果我试图输入重复的输入,它不会给我一个错误,但在我的redux控制台中,它已经存在了。当我再次提交表单时,它现在将显示'with err'。我一直在想办法,但似乎找不到任何解决办法。
const try = () => {
if (error !== null) {
console.log("with err");
} else if (error === null) {
console.log("no err");
}
};
我也遇到过这个问题。
-
一个正在捕获正在发送的请求的错误
-
另一个是捕获Redux端数据处理的错误
这是我以前用过的一个模式,你只需要确保你在每个级别上都处理了错误。
export const addCategory = ({ category, identifier, definition }) => async (dispatch) => { let response try { response = await axios.post( "http://localhost:5000/Admin/addCategory", { category, identifier, definition } ); dispatch({ type: "ADD_CATEG", payload: data }); } catch (error) { response = dispatch({ type: "GET_ERROR", payload: error.response.data.errorMessage, }); } if(response?.data){ // do stuff for success } // do stuff for errors };