如何在useEffect依赖数组中传递钩子的返回值?

时间:2021-05-13 09:27:10

标签: reactjs react-native

我需要在 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]);

1 个答案:

答案 0 :(得分:0)

大功告成,一些细节:

  1. 你不应该用 useHistory() 调用 new

  2. 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]);