我使用的是react-router-dom版本5.2.0
import { NavLink, useHistory } from "react-router-dom";
export const Login = () => {
const history = useHistory();
const userLogin = async () => {
const userResponse = await userLoginService(eMail, password);
console.log(userResponse.userResponse);
if (userResponse.userResponse.data) {
toast.success("You have successfully logged in");
history.push("/dashboard");
} else {
toast.error(userResponse.userResponse.error);
}
};
}
下面是我的登录按钮onClick
代码
<button className="btn mt-3 loginText" onClick={userLogin}>
Login
</button>
当我点击登录按钮API调用去后端,一旦得到响应,我将导航到仪表板屏幕,但它不工作…
如果我在函数顶部使用history.push
,它可以工作但如果我根据响应进行导航,它没有导航。
你需要先像这样调用useHistory
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
src: https://v5.reactrouter.com/web/api/Hooks
你试着用useNavigate
import { useNavigate } from "react-router-dom";
const navigate = useNavigate();
const redirectToHome = () => {
navigate("/home")
}
return (
<button type="button" onClick={redirectToHome}>
Home
</button>
);