You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

添加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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 10:18:26