我有用户在 localstorage 中,当用户注销时,localstorage 数据变为 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]);
现在,如果你看上面,在调度 signUp 操作后,我会回到 App.js,但这里 useEffect 不会运行,也不会检查用户是否已更改。
答案 0 :(得分:0)
嘿 - 看起来您缺少依赖项问题。你需要像这样
const getCartItems = useCallback(async () => {
if (user) {
console.log("Yes user exixts");
dispatch(getEachUserCart(user?.result?._id));
} else {
console.log("No user exist");
}
}, [user]);
否则,此函数将永远不会使用最新的用户值重新声明。如果这有帮助,请告诉我