添加usersSlice后Redux新增帖子报Cannot read properties of undefined错误
问题排查:Cannot read properties of undefined (reading 'substring')
错误原因
你的postsSlice.js中,prepare函数的位置错误,没有嵌套在postAdded reducer定义内。Redux Toolkit中,若要为某个reducer自定义prepare函数,需要将该reducer定义为包含reducer和prepare属性的对象。当前写法下,prepare是独立的reducer函数,postAdded使用默认的prepare逻辑,导致dispatch(postAdded(title, content, userId))时,action.payload仅为传入的title字符串,而非完整的post对象。最终posts数组中混入字符串类型元素,访问post.content会得到undefined,触发substring调用错误。
修复代码
修改postsSlice.js中的postAdded定义,将prepare嵌套进去:
import { createSlice, nanoid } from "@reduxjs/toolkit"; const initialState = [ { id: "1", title: "First Post!", content: "Hello!" }, { id: "2", title: "Second Post", content: "More text" } ]; const postsSlice = createSlice({ name: "posts", initialState, reducers: { // 将postAdded改为包含reducer和prepare的对象 postAdded: { reducer(state, action) { state.push(action.payload); }, prepare(title, content, userId) { return { payload: { id: nanoid(), title, content, user: userId } }; } }, postUpdated(state, action) { const { id, title, content } = action.payload; const existingPost = state.find((post) => post.id === id); if (existingPost) { existingPost.title = title; existingPost.content = content; } } } }); export const { postAdded, postUpdated } = postsSlice.actions; export default postsSlice.reducer;
验证要点
修复后可通过以下方式确认:
- 新增帖子后,在Redux DevTools中查看posts数组,新增元素应为包含
id、title、content、user属性的完整对象。 - PostList组件遍历posts时,每个post的
content属性均存在,substring调用不再报错。
内容的提问来源于stack exchange,提问作者mike
相关产品推荐
相关产品推荐

