Redux实现CRUD功能时array.find()报Cannot read properties of undefined错误
报错原因
报错本质是你调用.find()方法的目标值为undefined,结合代码来看有两个核心触发点:
- 第一版编辑页代码中,Redux取值key不匹配:你的store将帖子列表挂载在
state.loadPosts下,但代码中错误地从state.posts取值,该字段不存在自然为undefined - 存在id类型不匹配问题:你创建帖子用
nanoid()生成字符串id,但编辑页将路径取到的id用parseInt转为数字,匹配永远失败,同时未加空值防护
修复步骤
1. 统一Redux取值key + 加空值防护
将所有编辑页中获取单条帖子的代码统一修改为:
// 用可选链避免undefined调用find报错 const post = useSelector((state) => state.loadPosts?.find((post) => post.id === postId))
2. 修正id类型匹配
删掉编辑页中对postId的parseInt转换,保持字符串类型和nanoid生成的id一致:
// 原代码 const postId = parseInt(pathname.replace("edit-post/", "")) // 替换为 const postId = pathname.replace("/edit-post/", "")
3. 增加post不存在的兜底逻辑
在初始化title、content之前先判断post是否存在,避免二次报错:
if (!post) { return <div>帖子不存在或加载中</div> } const [title, setTitle] = useState(post.title) const [content, setContent] = useState(post.content)
4. 可选优化:阻止表单默认提交行为
编辑页的保存按钮点击会触发表单默认刷新,在提交方法中添加阻止默认事件逻辑:
const onSavePostClicked = (e) => { e.preventDefault() if (title && content) { dispatch(editPost({id: postId, title, content})) // 保存完成后关弹窗跳转回主页面 closeModal(false) navigation('/main') } }
内容的提问来源于stack exchange,提问作者Heitor Kenzou
相关产品推荐
相关产品推荐

