使用 Redux 时出现错误 - 未捕获类型错误:无法读取未定义的属性(读取“项目”)

问题描述 投票:0回答:1

我尝试使用 useSelector() 从 redux 存储中访问状态,但出现以下错误 -

AddToCart.jsx:7 Uncaught TypeError: Cannot read properties of undefined (reading 'items')
    at AddToCart.jsx:7:58
    at react-redux.js?v=afc4f5cf:189:28
    at memoizedSelector (react-redux.js?v=afc4f5cf:46:38)
    at getSnapshotWithSelector (react-redux.js?v=afc4f5cf:74:22)
    at mountSyncExternalStore (react-dom_client.js?v=afc4f5cf:11886:28)
    at Object.useSyncExternalStore (react-dom_client.js?v=afc4f5cf:12573:22)
    at useSyncExternalStore (chunk-4HAMFFQC.js?v=afc4f5cf:1120:29)
    at useSyncExternalStoreWithSelector3 (react-redux.js?v=afc4f5cf:81:23)
    at useSelector2 (react-redux.js?v=afc4f5cf:243:27)
    at AddToCart (AddToCart.jsx:7:19)

这是我的代码:-

store.js

import {configureStore} from '@reduxjs/toolkit';
import itemcountSliceReducer from './itemcountSlice'

const store = configureStore({
    reducer: {
        itemcountSliceReducer,
    }
})

export default store;

itemcountSlice.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    items: {
        1:0,
        2:0,
        3:0,
        4:0,
        5:0,
        6:0,
        7:0,
        8:0,
        9:0,
    },
    totalAmount: 0,
}

const itemcountSlice = createSlice({
    name : "itemcount",
    initialState,
    reducers : {
        addItem : (state,action) => {
            state.items = {...state.items, 
            [action.payload.id] : state.items[action.payload.id] + 1}
        },
        rmvItem : (state,action) => {
            state.items = {...state.items, 
                [action.payload.id] : state.items[action.payload.id] - 1}
        }
    }
})

export const {addItem,rmvItem} = itemcountSlice.actions;
export default itemcountSlice.reducer;

AddToCart.jsx

import React from 'react'
import { useSelector,useDispatch } from 'react-redux'
import {addItem} from '../store/itemcountSlice'


const AddToCart = ({id}) => { 
    const count = useSelector((state) => state.itemcount.items[id])
    const dispatch = useDispatch()
  return (
    <button onClick={(e) => dispatch(addItem(id))}>
            <img src = '../../assets/images/icon-add-to-cart.svg' alt = 'add to cart' /><span>Add to Cart</span>
    </button>
  )
}

export default AddToCart

应用程序.jsx

import { useState, useEffect } from 'react'
import './App.css'
import cardsData from '../data.json'
import Card from './components/Card'

function App() {
  const data = cardsData.map((item,i) =>(
    {...item, id : i + 1}
  ))

  return (
    <div className='main-container'>
      <div className='left-container'>
        <h1>Desserts</h1>
        <div className='cards-container' >
          {data.map((item) => 
            (<Card image = {item.image.desktop}
                category = {item.category}
                name = {item.name}
                price = {item.price} 
                key = {item.id} 
                id = {item.id}           
            />))}
        </div>
      </div>
      <div className='right-container'></div>
    </div>
  )
}

export default App

我的应用程序组件包含在 Provider 标签中,所以我不确定问题是什么。 当我使用 useSelector 时是否存在语法问题,或者我没有以正确的方式将减速器添加到存储中。我已经被困在这里有一段时间了,非常感谢任何帮助!

reactjs redux react-hooks react-redux
1个回答
0
投票

问题

您正在从

state.itemcount
中进行选择,但此 Redux 状态属性并不存在,因为您在创建商店时将其命名为
itemcountSliceReducer

const store = configureStore({
  reducer: {
    itemcountSliceReducer, // <-- state.itemcountSliceReducer
  }
})

解决方案

您正在创建的状态必须与您选择的状态相匹配。

将根状态重命名为

itemCount
,就像您选择的那样:

const store = configureStore({
  reducer: {
    itemCount: itemcountSliceReducer, // <-- state.itemcount
  }
})
const count = useSelector((state) => state.itemcount.items[id]);

或者更新选择器函数以匹配根状态标识符:

const store = configureStore({
  reducer: {
    itemcountSliceReducer, // <-- state.itemcountSliceReducer
  }
})
const count = useSelector((state) => state.itemcountSliceReducer.items[id]);
© www.soinside.com 2019 - 2024. All rights reserved.