我想在登錄后導航到儀表板并且儀表板是受保護的路線
const handleLogin = (e) => {
e.preventDefault();
if (email || password) {
dispatch(loginUser({ email, password }));
navigate("/dashboard");
} else {
toast.error("Please Enter Email and Password");
}
};
我正在使用 redux 工具包 createAsyncThunk 進行 api 請求
export const loginUser = createAsyncThunk("auth/login", async (userDetails) => {
try {
const { email, password } = userDetails;
const res = await fetch("http://localhost:5000/api/users/login", {
method: "post",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
email,
password,
}),
});
const result = await res.json();
if (result.error) {
toast.error(result.error);
} else {
toast.success("Login successfull");
localStorage.setItem("user", JSON.stringify(result));
return result;
}
} catch (error) {
console.log(error);
}
});
當我單擊登錄時,它嘗試在狀態更新之前導航頁面我想要導航功能等到 api 回應收到然后導航到儀表板
uj5u.com熱心網友回復:
dispatch(loginUser({ email, password }));回傳一個承諾,您可以等待承諾解決,然后再進行其他作業:
const handleLogin = () => {
dispatch(loginUser({ email, password })).then(() => {
navigate("/dashboard");
})
}
請參閱展開結果操作
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442726.html
