React-Redux博客应用中用户ID匹配作者名显示undefined问题求助
React-Redux博客应用:作者名显示undefined问题排查与解决
问题现象
使用Redux Toolkit构建博客应用时,新增博客的标题、内容能正常渲染,但通过用户ID匹配作者名时,始终显示undefined(最终显示"Unknown author")。
问题根源
类型不匹配导致查找失败:
usersSlice中存储的用户ID是数字类型(如{id:0, name: 'Dude Lebowski'})- 从
AddPostForm的<select>组件获取的userId是字符串类型(HTML表单元素的value默认都是字符串) - 在
PostAuthor组件中使用user.id === userId做严格相等比较时,数字与字符串无法匹配,users.find()返回undefined
解决方案
方案1:在表单中转换userId为数字类型
修改AddPostForm中的状态更新逻辑,将字符串类型的ID转为数字:
// 初始状态改为null,对应空选项 const [userId, setUserId] = useState(null) // 处理选择事件时转换类型 const onAuthorChanged = e => { const value = e.target.value setUserId(value ? Number(value) : null) }
同时调整保存按钮的可用判断逻辑:
const canSave = Boolean(title) && Boolean(content) && userId !== null
方案2:在PostAuthor中兼容类型比较
修改PostAuthor中的查找条件,通过类型转换或松散相等实现匹配:
// 方式A:主动将userId转为数字后严格比较 const author = users.find(user => user.id === Number(userId)); // 方式B:使用松散相等(自动转换类型) const author = users.find(user => user.id == userId);
额外优化(可选)
如果需要让初始示例博客也显示作者名,需给postsSlice的initialState中的帖子补充userId字段:
const initialState = [ {id: '1', title: 'Learning redux toolkit', content:'...', userId: 0}, {id: '2', title: 'Slices...', content:'...', userId: 1} ]
内容的提问来源于stack exchange,提问作者Josh Simon
相关产品推荐
相关产品推荐

