【问题标题】:How to save state in localStorage using redux toolkit on nextjs project如何在 nextjs 项目中使用 redux 工具包在 localStorage 中保存状态
【发布时间】:2021-10-12 21:05:34
【问题描述】:

我想将更新后的状态保存到 localStorage,但尝试此操作时遇到错误。 localstorage is not defined

cartSlice.jsx

import {v4 as uuid} from "uuid";
import {createSlice} from "@reduxjs/toolkit";
const data = JSON.parse(localStorage.getItem('cart'));
export const cartSlice = createSlice({
  name: 'shoppingCart',
  initialState: data ? data : [],
  reducers: {
    addToCart: (state, action) => {
        const product = action.payload;
        const productInCart = state.find(item => item.id === product.id && item.color === product.color && item.size === product.size && item.material === product.material);

        if (productInCart) {
            const cartProductIndex = state.findIndex(item => item.id === product.id);
            state[cartProductIndex].quantity = state[cartProductIndex].quantity + product.quantity;
        } else {
            product['cartId'] = uuid();
            return [product, ...state];
        }

        localStorage.setItem('cart', JSON.stringify(state));
    }
}
})

cartAction.js

import {addToCart} from "@slices/cartSlice";

export const addToCartAction = (payload) => (dispatch) => {
 dispatch(addToCart(payload))
}

如何解决?

【问题讨论】:

  • 什么 是错误?试图从这里JSON.parse(localStorage.getItem('cart')); 解析本地存储中的空/未定义购物车状态?
  • @DrewReese 错误是localstorage is not defined
  • 哦,我看到你在标题中提到了 Nextjs,是的,我认为 localStorage 在 SSR 中不可用。我不确定这里的最佳解决方案,但我怀疑它会涉及当组件安装在某处时在客户端初始化某些状态。
  • 我假设您要么必须禁用服务器端呈现,要么确保代码仅在客户端执行。
  • addToCartAction 应该没问题,只有在按下按钮时才会执行(我假设)。问题是 createSlice 在导入、服务器和客户端上执行。

标签: reactjs redux local-storage redux-toolkit


【解决方案1】:

一般来说,已经有很多关于这在 SSR 中不起作用的说法。 但与此无关:您的 redux reducer 中不能有副作用,这就是这样的副作用之一。只是不允许这样。

相反,要么使用store.subscribe 编写您自己的实现,要么使用redux-persist。由于后者是一个已经记录在案的库,我可能会选择后者。但是,在这两种情况下,在执行任何有关 localStorage 的操作之前,您始终必须检查您是否在客户端而不是服务器上,因此将其包装到 if 块中并在调用之前检查 window.localStorage 是否为 undefined (或初始化 redux-persist)。

【讨论】:

    【解决方案2】:

    解决办法是

    const data = typeof window !== "undefined" && localStorage.getItem("cart") ? 
     JSON.parse(localStorage.getItem("cart")) : []

    【讨论】:

    • 感谢您的回答,但如果您添加一些解释可能会更好。
    【解决方案3】:

    您可以改用 Cookie。另一种解决方案是使用node-localstorage

    var LocalStorage = require('node-localstorage').LocalStorage,
    localStorage = new LocalStorage('./storage')
    

    【讨论】:

    • node-localstorage 不会真正有用(可能相反),因为每个用户都会有相同的。
    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2022-01-15
    • 2021-11-29
    • 2022-06-15
    • 2012-10-01
    • 2021-09-15
    • 2021-03-11
    • 2021-06-20
    相关资源
    最近更新 更多