[英]LocalStorage doesn't stay updated on page refresh in MERN Application
LocalStorage 不希望在刷新页面上保持更新。 我不确定为什么会这样,我的错误在哪里。 后端更新正常,但 localStorage 没有保持更新。
这是我更新localStorage的地方:
const UserContextProvider = (props) => {
const [user, setUser] = useState({})
const [cart, setCart] = useState(localStorage.getItem("cart") || [])
useEffect(() => {
fetch(`${API}/auth/user`, {
method: 'GET',
withCredentials: true,
credentials: 'include'
})
.then (response => response.json())
.then (response => {
setUser(response.user)
})
.catch (error => {
console.error (error);
});
}, [setUser])
useEffect(() => {
localStorage.setItem("cart", JSON.stringify(user.cart))
}, [setUser])
const addToCart = (user, product) => {
fetch(`${API}/cart/usercart`, {
method:"POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify([user._id, product])
})
.then(() => setUser({...user, cart: [...user.cart, product]}))
.catch(error => console.log(error))
}
return (
<UserProvider value={[user, setUser, addToCart, cart]}>
{props.children}
</UserProvider>
)
}
export default UserContextProvider;
这是我尝试使用它的组件:
const Cart = props => {
const [user, setUser, cart] = useContext(UserContext)
...
{cart?.length === 0 ? <></> :
<>
{cart?.map(product => {
return(...)
以下代码仅在组件挂载时运行一次:
useEffect(() => {
setCart(JSON.parse(localStorage.getItem("cart")) || [])
}, []);
为了呈现最新值,您必须依赖道具或购物车更新时更新的东西:
useEffect(() => {
setCart(JSON.parse(localStorage.getItem("cart")) || [])
}, [props.something]);
根据您的实现,我建议让您的 contextProvider 提供此数据,而不是组件本身在每次渲染时从 localStorage 中检索它。 应用程序启动时,您只需要 localStorage 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.