Redux initialState缺少一个键值对

n1bvdmb6  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(163)

所以我有一个react typescript应用程序,里面有redux(toolkit+thunk),下面是reducer:

import { createSlice } from "@reduxjs/toolkit";
import { findProduct } from "../helpers";
import { CartItem, Product } from "../types";

interface InitialState {
  cart: CartItem[];
  products: Product[];
}

const initialState: InitialState = {
  cart: [],
  products: [
    {
      name: "Pencil",
      availability: 24,
      price: 114,
      _uuid: "b7b0e060-e090-11ed-b5ea-0242ac120002",
    },
    {
      name: "Pen",
      availability: 12,
      price: 154,
      _uuid: "a300d6d8-e091-11ed-b5ea-0242ac120002",
    },
    {
      name: "Eraser",
      availability: 8,
      price: 135,
      _uuid: "a9a60f4e-e091-11ed-b5ea-0242ac120002",
    },
  ],
};

export const cart = createSlice({
  name: "cart",
  initialState,
  reducers: {}
});

export default cart.reducer;
import './App.scss';
import { useSelector, useDispatch } from 'react-redux';
import { IRootState, Product } from './types';

function App() {

  const dispatch = useDispatch();

  const products = useSelector((state: IRootState) => state.cart.products);
console.log(products)

  return (
    <div className="App h-screen w-screen">
        <div className=''>
        {products.map(product => (
          <div key={product._uuid} className='flex justify-between bg-emerald-200 my-2 p-2'>
            <h1>{product.name}</h1>
            <button onClick={() => addToCart(product)}>addToCart</button>
          </div>
        ))}
        </div>
    </div>
  )
}

export default App

我现在想访问products并Map到它上面,正如您在第二个代码片段中看到的,但是由于某些原因,当我登录时,状态上缺少products键值对,但显示了cart。

hts6caw3

hts6caw31#

好吧,我找到问题了。
我需要清除我的localStorage来删除持久状态对象,因为它与新的初始状态不同。

相关问题