javascript - 更新数组对象内的值
问题描述
我只想name
用用户输入的新名称替换。我正在使用 react redux 打字稿,事实证明它非常困难。所有传入的参数都有效,newName
and index
,我只需要更新数组对象然后返回它,只更改索引对象中的名称。
我的代码:
行动:
export const updateName = (newName: string, index: number) => (
dispatch: (arg0: { type?: string; newName: string; index: number }) => any
) => {
dispatch({
type: UPDATE_NAME,
newName,
index
});
};
减速器:
case UPDATE_NAME:
return {
...state
items[action.index].name: action.newName,
};
状态如下所示:
items: Array(50)
0: {id: "1d0b1095-f0b4-4881-8d5e-74c86d5beee2", name: "A Ipsum Debitis", participants: {…},
1: {id: "7384a574-1592-484e-9404-e876bf45410c", name: "Distinctio Blanditiis Voluptatibus Ut", participants: {…},
解决方案
除了浅拷贝状态对象外,您还需要浅拷贝任何正在更新的嵌套状态,即正在更新state.items
的特定数组元素。
case UPDATE_NAME:
return {
...state,
items: state.items.map((el, i) => i === action.index ? {
...el,
name: action.newName,
} : el),
};
推荐阅读
- javascript - 无法更改 this.state 属性:无法读取未定义的属性“setState”
- angular - 有人可以用 Angular 形式解释我的这种语法吗#name="ngModel"
- c# - 将彩色非 ASCII 字符打印到 CLI
- monitoring - 使用 java datadog 代理发送 KafkaStreams jmx 指标
- python - 照片转换 2d 黑白到 3d rgb 照片
- spring-boot - 是否对 Integer 字段进行任何验证以检查 rest api 的确切值?@Min 和 @Max 不起作用
- reactjs - 无法在测试中访问 IonInput 值
- javascript - 链接内的单独值
- python - 如何自动替换在 QtPlainTextEdit 小部件中键入的字符
- ios - SwiftUI:有没有办法向 Menu() 添加自定义按钮样式?