首页 > 解决方案 > Redux - 更新对象数组中的值

问题描述

我想从我的数组 onClick 更新一个属性。我怎么能访问一个特定的笔记,知道我已经通过数组映射来显示它?我想在点击时修改“描述”。

我的数据:

export const NOTES = [
  {
    description: "My description",
    id: 0,
  },
  {
    description: "My description",
    id: 1,
  }
]

我的减速机:

import { NOTES } from '../../../../shared/spec-ressources/notes'

const INITIAL_STATE: any[] = [...NOTES];

export const reducer = (state: any[] = INITIAL_STATE, action: any) => {
  switch (action.type) {
    default:
      return state;
  }
}


export default reducer;

标签: reactjsredux

解决方案


首先,您需要一个正确的操作名称,例如,我们生成更新操作和删除操作来处理您的数据:

在您的操作文件中:

const UPDATE_DESCRIPTION = "UPDATE_DESCRIPTION";
const DELETE_DESCRIPTION = "DELETE_DESCRIPTION";

const updateDescription = (newData) => ({type: UPDATE_DESCRIPTION, payload: newData)}

const deleteDescription = (id) => ({type: DELETE_DESCRIPTION, payload: id})

现在将动作名称导入reducer,并在组件/视图/页面中导入动作方法以触发动作。

在减速器中:

import { NOTES } from '../../../../shared/spec-ressources/notes'
import {UPDATE_DESCRIPTION ,DELETE_DESCRIPTION } from 'actions'; // --> add your action path here

const INITIAL_STATE: any[] = [...NOTES];

export const reducer = (state: any[] = INITIAL_STATE, action: any) => {
  switch (action.type) {
    case(UPDATE_DESCRIPTION):
      return {
        ...state,
        notes: state.notes.map(note => note.id === action.payload.id ? {
            ...note,
            description: action.payload.newDescription
          } : note)
    }
    case (DELETE_DESCRIPTION):
      return{
        ...state,
        notes: satet.notes.filter(note => note.id !== action.payload.id)
      }
    default:
      return state;
  }
}


export default reducer;

注意 1:关于您的帖子的新数据应包含一个iddescription哪个 id 是您希望更新的帖子,描述是通过updateDescription方法调度操作到达的新描述(更新的描述)。

注意 2:这是您的 redux/action/reducer 的基本和纯粹的实现,您可以使用不同的 redux 助手库自定义它,但结构是相同的。


推荐阅读