Redux中如何更新对象数组内指定元素的description属性
解决方案
1. 实现思路
- 遵守reducer的不可变更新原则,不得直接修改原state数组或数组内的笔记对象
- 遍历state数组时匹配对应id的笔记,匹配到就返回更新了description属性的新对象,未匹配直接返回原对象即可
2. 调整reducer代码
import { NOTES } from '../../../../shared/spec-ressources/notes' const INITIAL_STATE: any[] = [...NOTES]; export const reducer = (state: any[] = INITIAL_STATE, action: any) => { switch (action.type) { // 新增更新笔记描述的分支逻辑 case 'UPDATE_NOTE_DESCRIPTION': const { id, newDescription } = action.payload return state.map(note => { // id匹配时返回更新属性后的新对象 if (note.id === id) { return { ...note, description: newDescription } } // 不匹配直接返回原对象,不做修改 return note }) default: return state; } } export default reducer;
3. 点击事件中触发更新
渲染笔记列表时,在对应元素的点击回调中dispatch对应action即可,示例如下:
// 假设组件内已通过useSelector拿到笔记列表、useDispatch拿到dispatch方法 {notes.map(note => ( <div key={note.id}> <p>{note.description}</p> <button onClick={() => { // 此处newDescription可替换为实际业务值,比如输入框的输入内容 dispatch({ type: 'UPDATE_NOTE_DESCRIPTION', payload: { id: note.id, newDescription: '更新后的描述内容' } }) }} > 修改笔记描述 </button> </div> ))}
内容的提问来源于stack exchange,提问作者MrVoland
相关产品推荐
相关产品推荐

