【问题标题】:LocalStorage doesn't stay updated on page refresh in MERN ApplicationLocalStorage 不会在 MERN 应用程序中的页面刷新时保持更新
【发布时间】:2021-08-01 01:41:39
【问题描述】:

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(...)

【问题讨论】:

    标签: node.js reactjs mongodb express mern


    【解决方案1】:

    以下代码仅在组件挂载时运行一次:

    useEffect(() => {
      setCart(JSON.parse(localStorage.getItem("cart")) || [])
    }, []);
    

    为了呈现最新值,您必须依赖道具或购物车更新时更新的东西:

    useEffect(() => {
      setCart(JSON.parse(localStorage.getItem("cart")) || [])
    }, [props.something]);
    

    根据您的实现,我建议让您的 contextProvider 提供此数据,而不是组件本身在每次渲染时从 localStorage 中检索它。您只需要应用启动时的 localStorage 值。

    【讨论】:

    • 但它应该在页面刷新时工作,不是吗?
    • 但它现在甚至没有将数据保存在localStorage中
    • 我放入了useEffect依赖数组“setUser”,因为当我在函数中添加产品时我正在更改它。但是现在本地存储是空的,我不能像以前那样在 Cart 组件中映射购物车
    • @hendra 你可以检查一下。我添加了整个 Context 和 Cart 组件。
    猜你喜欢
    • 1970-01-01
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多