React Native中如何在map/filter后更新数组指定项的特定字段?
React Native中更新数组指定项的特定字段
你的问题出在对数组方法和state更新的逻辑理解上,直接上正确实现:
this.state = { post: [{ id: "0", author: "Duffy Duck", delay: "1", picture: "" }] } putpicture(id) { const picture_new = "/gggg(yyb45789986..." // 遍历原数组生成新数组:匹配项更新picture字段,其余项保持原样 const updatedPosts = this.state.post.map(item => { if (item.author === id) { // 用扩展运算符复制原对象属性,再覆盖picture字段,避免直接修改原state数据 return { ...item, picture: picture_new } } return item }) // 一次性更新state中的post数组 this.setState({ post: updatedPosts }) }
关键说明:
- 不需要用
filter,因为我们要保留数组里的所有项,仅修改匹配到的条目 - 用
map遍历数组,对每个条目做判断:如果author和传入的id匹配,就返回一个包含新picture字段的新对象;不匹配的条目直接返回原对象 - 必须一次性调用
setState更新整个post数组,不能在循环里多次调用setState(会触发不必要的重复渲染)
执行后,你的state会更新为目标格式:
[{ id:"0", author:"Duffy Duck", delay:"1", picture:"/gggg(yyb45789986..." }]
内容的提问来源于stack exchange,提问作者Elly
相关产品推荐
相关产品推荐

