首页 > 解决方案 > 本地存储数据更改后的 Reactjs 状态更新

问题描述

我有本地存储中的用户,当用户注销时本地存储数据变为 NULL。当用户登录时,localstorages 会填充用户的数据,但要检查这一点,我在 App.js 中的 userEffect 没有反映任何变化。

我有注册

  dispatch(signin(form, history));
  history.push("/");                    //go back to App.js file

在导航栏中,用户数据发生变化

  const Navbar = (props) => {
  const [user, setUser] = useState(JSON.parse(localStorage.getItem("profile"))); 

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

现在在 App.js 我有

 const user = JSON.parse(localStorage?.getItem("profile"));
 const getCartItems = useCallback(async () => {
 if (user) {
   console.log("Yes user exixts");
   dispatch(getEachUserCart(user?.result?._id));
  } else {
   console.log("No user exist");
  }
}, []); //

useEffect(() => {
  getCartItems();
}, [getCartItems]);

现在如果你看上面,在发送注册操作后,我回到 App.js 但这里 useEffect 不运行也不检查用户是否已更改。

标签: javascriptreactjsreduxreact-redux

解决方案


嘿——看起来你有一个缺少依赖的问题。你需要这样

const getCartItems = useCallback(async () => {
 if (user) {
   console.log("Yes user exixts");
   dispatch(getEachUserCart(user?.result?._id));
  } else {
   console.log("No user exist");
  }
}, [user]);

否则,该函数将永远不会用最新的用户值重新声明。请让我知道这是否有帮助


推荐阅读