问题描述
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,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 值。