简体   繁体   English

如何将 redux 工具包初始 state 设置为 object 数组或带有 Z1E35BCBA25DBA1089C8F7BD08 的本地存储?

[英]How to set a redux toolkit initial state to an array of object or localstorage with typescript?

i'm currently trying to set an initialState (items) to an array of object or the same thing from the localStorage.我目前正在尝试将初始状态(项目)设置为 object 数组或来自 localStorage 的相同内容。 The problem is, that i'm receiving this kind of error.问题是,我收到了这种错误。

Type 'number' is not assignable to type '{ id: string;类型 'number' 不能分配给类型 '{ id: string; price: number;价格:数量; quantity: number;数量:数量; totalPrice: number;总价格:数字; name: string;名称:字符串; }[]'.ts(2322) cart.ts(4, 3): The expected type comes from property 'items' which is declared here on type 'SliceState' }[]'.ts(2322) cart.ts(4, 3): 预期的类型来自属性 'items',它在类型 'SliceState' 上声明

type SliceState = {
  items: {
    id: string;
    price: number;
    quantity: number;
    totalPrice: number;
    name: string;
  }[];
  totalQuantity: number;
  totalPrice: number;
};

const initialState: SliceState = {
  items: [] | localStorage.getItem("cart"),
  totalQuantity: 0,
  totalPrice: 0,
};


const cartSlice = createSlice({
  name: "cart",
  initialState,
  reducers: {
    addItemToCart(state, action: PayloadAction<any>) {
      const newItem = action.payload;
      const existingItem = state.items.find((item) => item.id === newItem.id);
      state.totalQuantity++;
      if (!existingItem) {
        state.items.push({
          id: newItem.id,
          price: newItem.price,
          quantity: newItem.quantity,
          totalPrice: newItem.price * newItem.quantity,
          name: newItem.name,
        });
      } else {
        existingItem.quantity += action.payload.quantity;
        existingItem.totalPrice =
          existingItem.totalPrice + newItem.price * newItem.quantity;
      }
      localStorage.setItem("cart", JSON.stringify(state.items));
}
}

Is there any way to achieve what i'm trying to do?有什么办法可以实现我想要做的事情吗? I'm also using nextjs, i know ssr can be a problem with localstorage.我也在使用 nextjs,我知道 ssr 可能是 localstorage 的问题。

You are using incorrect syntax here:您在这里使用了不正确的语法:

items: [] | localStorage.getItem("cart")

What you meant is:你的意思是:

items: localStorage.getItem("cart") || []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM