如何解决“未捕获的类型错误:无法读取未定义的属性(读取‘测验’)”Redux 选择器
2022-12-22
306
我对 redux 还很陌生。
我似乎无法弄清楚为什么我的 redux 选择器
export const quizzesSelector = (state) => state.quizzes.quizzes;
在第 31 行会产生“Uncaught TypeError: Cannot read properties of undefined (reading '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;
2个回答
尽管这里可以建议很多事情来获取商店值,但您应该在显示的文件中执行此操作
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
Rahul Purohit
2022-12-22
我找到了答案。测验状态显示为未定义的原因是它从未导入到商店中。
虽然我知道
createSlice
会自动生成与减速器和状态相对应的动作创建者和动作类型。出于某种原因,我脑子里想着一旦你导出默认的
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 },
});
LM17
2022-12-23