reactjs Redux Error(无法读取未定义的属性(阅读'items'))for export const selectItems =(state)=>state,basket.items;

i34xakig  于 2023-04-29  发布在  React
关注(0)|答案(2)|浏览(72)

在我的电子商务网站Nextjs中,我试图使用redux实现添加到购物篮功能,但错误“无法读取未定义的属性(阅读'items'):export const selectItems =(state)=〉state.basket.items;“不断发生。下面是我的代码
Store.js

import { configureStore } from "@reduxjs/toolkit";
import { basketReducer } from "./Slices/basketSlice";

export const store = configureStore({
  reducer: {
    basket: basketReducer,
  },
});

Slices/basketSlice.js

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

// const initialState = {
//   items: [],
// };

export const basketSlice = createSlice({
  name: "basket",
  initialState: { items: [] },
  reducers: {
    addToBasket: (state, action) => {
      state.items = [...state.items, action.payload];
    },
    removeFromBasket: (state, action) => {},
  },
});

// Action creators are generated for each case reducer function
export const { addToBasket, removeFromBasket } = basketSlice.actions;
export const selectItems = (state) => state.basket.items;
export default basketSlice.reducer;
sd2nnvve

sd2nnvve1#

使用

import basketReducer from "./Slices/basketSlice";

Store.js中导入默认导出为basketReducer。您现在使用的方法是尝试导入名为basketReducer的导出符号,该符号不存在。或者,您可以使用

export const basketReducer = basketSlice.reducer;

Slices/basketSlice.js中以您要导入的名称导出减速器。

jbose2ul

jbose2ul2#

在要使用此状态的组件中尝试此操作

import { useSelector } from "react-redux";
const component = () => {
  const selectItems = (state) => 
  useSelector((state)=>state.basket.items);
  return <></>;
}

相关问题