【问题标题】:React Hook useEffect has missing dependencies: 'dispatch' and 'logout'. Either include them or remove the dependency arrayReact Hook useEffect 缺少依赖项:“dispatch”和“logout”。包括它们或删除依赖数组
【发布时间】:2021-04-14 14:42:50
【问题描述】:

我不明白这段代码有什么问题。大多数时候我都面临这个问题,但仍然无法解决。

const logout = () => {
    dispatch({ type: "LOGOUT" });
    dispatch({
      type: "EMPTY_CART",
    });
    history.push("/");
    setUser(null);
  };

  useEffect(() => {
    dispatch(getEachUserCart(user?.result?._id));

    const token = user?.token;
    setShowCartInfor(false);
    // JWT..
    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }
    setUser(JSON.parse(localStorage.getItem("profile")));
  }, [location, user?.result?._id, user?.token]);

【问题讨论】:

  • 但我需要稍后调用该函数。例如,每当我单击注销按钮时,都会触发注销功能。

标签: reactjs redux


【解决方案1】:

警告由您的 linter 报告,表示您需要根据您在组件中使用的闭包值提供依赖数组。

要修复警告,您可以将代码更新为 add logout as a dependencyuseEffect 并使用 useCallback 声明注销功能

const logout = useCallback(() => {
    dispatch({ type: "LOGOUT" });
    dispatch({
      type: "EMPTY_CART",
    });
    history.push("/");
    setUser(null);
  }, [history, dispatch, setUser]);

  useEffect(() => {
    dispatch(getEachUserCart(user?.result?._id));

    const token = user?.token;
    setShowCartInfor(false);
    // JWT..
    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }
    setUser(JSON.parse(localStorage.getItem("profile")));
  }, [location, user?.result?._id, user?.token, logout]);

如果没有从其他地方调用,您也可以通过在 useEffect 中移动注销功能来修复警告

useEffect(() => {
    
    const logout = () => {
        dispatch({ type: "LOGOUT" });
        dispatch({
          type: "EMPTY_CART",
        });
        history.push("/");
        setUser(null);
      };
    dispatch(getEachUserCart(user?.result?._id));

    const token = user?.token;
    setShowCartInfor(false);
    // JWT..
    if (token) {
      const decodedToken = decode(token);

      if (decodedToken.exp * 1000 < new Date().getTime()) logout();
    }
    setUser(JSON.parse(localStorage.getItem("profile")));
  }, [location, user?.result?._id, user?.token]); 

【讨论】:

  • 感谢第一个解决方案运行良好。你能解释一下为什么会这样吗?
  • React 钩子的工作原理是 javascript 中的闭包。所以如果你没有在依赖数组中指定一个值,那么如果该值发生变化,useEffect 将不会运行。通常函数不会改变,但如果它们使用闭包中的某些值,它们需要接收更新值。这就是为什么 eslint 缺少依赖规则会警告用户添加在代码块中使用的适当依赖项,以避免与闭包相关的意外问题。
  • @MuhammadHassaanAther 如果有帮助,请考虑将答案标记为已接受
猜你喜欢
  • 2023-04-09
  • 2020-07-19
  • 2020-11-05
  • 2021-10-29
  • 2020-05-31
  • 1970-01-01
  • 2021-05-07
  • 2021-08-24
  • 1970-01-01
相关资源
最近更新 更多