reactjs - 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;
解决方案
首先,您需要一个正确的操作名称,例如,我们生成更新操作和删除操作来处理您的数据:
在您的操作文件中:
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:关于您的帖子的新数据应包含一个id
,description
哪个 id 是您希望更新的帖子,描述是通过updateDescription
方法调度操作到达的新描述(更新的描述)。
注意 2:这是您的 redux/action/reducer 的基本和纯粹的实现,您可以使用不同的 redux 助手库自定义它,但结构是相同的。
推荐阅读
- javascript - 如何将变量键入为对象的任何潜在属性?
- amazon-web-services - 为 S3 存储桶中的特定文件夹创建 CloudFormation 堆栈
- c++ - v 在不同的 .cpp 文件中使用在 main.cpp 中创建的类型的对象
- git - Github主分支和主分支的区别?
- openssl - 使用 openssl 以特定格式创建 RSA 密钥
- python - 更高维度的 KMeans 聚类是否可行?
- r - 强制 rsconnect::deployApp() 无法测试“on.failure”
- javascript - 如何创建复制到剪贴板?将数据从 h1 标签复制到输入(反应)
- asp.net-core - 无法更新一对多关系(尝试边做边学)
- ruby-on-rails - 在 ElasticSearch 结果中生成/添加搜索词