如何解决“未捕获的TypeError:无法读取未定义(阅读“quizzes”)”Redux选择器的属性

tjvv9vkg  于 2022-12-23  发布在  其他
关注(0)|答案(2)|浏览(141)

我对还原还很陌生。
我似乎无法解决为什么我的redux选择器export const quizzesSelector = (state) => state.quizzes.quizzes;在第31行生成“未捕获的TypeError:无法读取未定义的属性(阅读“quizzes”)”错误。
我哪里出错了?为什么这个阅读是未定义的?如果找到了,一个小的解释会很好,因为我仍然试图把我的头围绕在状态,存储,调度等。
谢啦,谢啦

import { createSlice } from "@reduxjs/toolkit";
import { addQuizId } from "../topics/topicsSlice";

const quizzesSlice = createSlice({
  name: "quizzes",
  initialState: {
    quizzes: {}
  },
  reducers: {
    addQuiz: (state, action) => {
      const { quizId, name, topicId, cardIds } = action.payload;
      state.quizzes[quizId] = {
        id: quizId,
        name: name,
        topicId: topicId,
        cardIds: cardIds
      };
    }
  }
});

// thunk to quizz to the related topic
export const addQuizAndQuizId = (quiz) => {
  const { quizId, name, topicId, cardIds } = quiz;
  return (dispatch) => {
    dispatch(quizzesSlice.actions.addQuiz(quiz)); // dispatch the new quiz
    dispatch(addQuizId({ quizId: quizId, topicId: topicId })); // Dispatch the new quiz and topic id
  };
};

export const quizzesSelector = (state) => state.quizzes.quizzes;

export const { addQuiz } = quizzesSlice.actions;

export default quizzesSlice.reducer;
62o28rlo

62o28rlo1#

虽然这里可以建议您做很多事情来获取存储值,但您应该在显示的文件中执行此操作

import { createStore } from 'redux'

const store = createStore(reducer)

必须将此商店添加到应用的根目录。
无论在什么地方(组件),您现在需要使用状态或分派任何操作,您都可以简单地这样做

import { useSelector, useDispatch } from 'react-redux'

const count = useSelector((state) => state.counter.quizzes)

我建议您给予此快速入门指南https://redux-toolkit.js.org/tutorials/quick-start

zi8p0yeb

zi8p0yeb2#

我找到了答案。Quizzes状态阅读undefined的原因是因为它从未导入到存储中。
虽然我知道createSlice会自动生成对应于reducer和state的action创建者和action类型,但出于某种原因,我认为一旦导出默认的slice.reducer,它会自动将其添加到存储中。
在查看了我的商店后,我意识到它不在那里,我必须将它导入到configureStore

import { configureStore } from "@reduxjs/toolkit";
import topicsReducer from "../features/topics/topicsSlice";
import quizzesReducer from "../features/quizzes/quizzesSlice"; // This was not there originally 

export default configureStore({
  reducer: { topics: topicsReducer, quizzes: quizzesReducer },
});

相关问题