我需要在 isLogin 函数中使用历史记录,但根据 React 指南,我们不应该在钩子中使用钩子。如果我在 useCallback 依赖项数组中传递历史记录,它会告诉我记住“历史记录”值。同样,这将是钩子的嵌套。
const [values, setValues] = useState(inititalValues);
const history = new useHistory();
const isLogin = useCallback(() => {
if (!localStorage.getItem("token")) {
history.push("/");
toast.error("Please Login");
}
}, []);
useEffect(() => {
isLogin();
}, [isLogin]);
答案 0 :(得分:0)
大功告成,一些细节:
你不应该用 useHistory()
调用 new
。
history
在调用之间不会改变,因此您基本上可以在依赖项中使用它:
const [values, setValues] = useState(inititalValues);
const history = useHistory(); // no 'new' keyword
// The following code will only happen once when the component is "mounted":
useEffect(() => {
if (!localStorage.getItem("token")) {
history.push("/");
toast.error("Please Login");
}
}, [history]);