【问题标题】:Reactjs state update after localstorage data changes本地存储数据更改后的 Reactjs 状态更新
【发布时间】:2021-04-14 12:14:37
【问题描述】:

我有本地存储中的用户,当用户注销时本地存储数据变为 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 不运行也不检查用户是否已更改。

【问题讨论】:

    标签: javascript reactjs redux react-redux


    【解决方案1】:

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

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

    否则,此函数将永远不会使用最新的用户值重新声明。如果有帮助,请告诉我

    【讨论】:

    • 啊——让我在本地运行它看看发生了什么!
    • 在我这边正确渲染,我没有的一件事是发送到getEachUserCart 所以这个动作可能有问题?它会以某种方式改变用户对象吗?
    猜你喜欢
    • 2016-10-02
    • 2018-07-08
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-04
    • 2021-04-27
    相关资源
    最近更新 更多