javascript - 本地存储数据更改后的 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 不运行也不检查用户是否已更改。
解决方案
嘿——看起来你有一个缺少依赖的问题。你需要这样
const getCartItems = useCallback(async () => {
if (user) {
console.log("Yes user exixts");
dispatch(getEachUserCart(user?.result?._id));
} else {
console.log("No user exist");
}
}, [user]);
否则,该函数将永远不会用最新的用户值重新声明。请让我知道这是否有帮助
推荐阅读
- php - 如何在 WooCommerce 中为未登录用户禁用特定插件?
- sql - 我如何通过多个表获得平均值
- python - Python Django Int 的无效输入语法错误,即使它不应该是整数
- javascript - 已解决:如何根据 promise 的响应打破 for 循环?
- html - 如何在悬停时清除a.class css中的:之前的文本装饰?
- javascript - 在图标选择上显示文本选择了多少个图标
- selenium-webdriver - 如何使用数据生成器运行 TestNG.xml
- r - 分隔具有不同长度的行值并删除其中一个值
- google-sheets - 谷歌表格查询计数返回“计数”而不是数值
- angular - 如何在实用程序类中注入 ng-bootstrap NgbDateParserFormatter