javascript - 根据 ID 在 React 中编辑对象数组中的属性
问题描述
我有一个像这样在新的“上下文 API”中创建的对象数组......
const reducer = (state, action) => {
switch (action.type) {
case "DELETE_CONTACT":
return {
...state,
contacts: state.contacts.filter(contact => {
return contact.id !== action.payload;
})
};
default:
return state;
}
};
export class Provider extends Component {
state = {
contacts: [
{
id: 1,
name: "John Doe",
email: "jhon.doe@site.com",
phone: "01027007024",
show: false
},
{
id: 2,
name: "Adam Smith",
email: "adam.smith@site.com",
phone: "01027007024",
show: false
},
{
id: 3,
name: "Mohammed Salah",
email: "mohammed.salah@site.com",
phone: "01027007024",
show: false
}
],
dispatch: action => {
this.setState(state => reducer(state, action));
}
};
render() {
return (
<Context.Provider value={this.state}>
{this.props.children}
</Context.Provider>
);
}
}
我想在“reducer”中创建一个操作,允许我根据我将作为有效负载传递给操作的 ID 编辑每个联系人的“显示”属性,我该怎么做?
解决方案
为避免数组突变并在编辑联系人时保留元素位置,您可以执行以下操作:
case "EDIT_CONTACT":
const { id, show } = action.payload;
const contact = { ...state.contacts.find(c => c.id === id), show };
return {
...state,
contacts: state.contacts.map(c => {return (c.id !== id) ? c : contact;})
};
推荐阅读
- integromat - 如何在自定义 Integromat 应用程序中调试 IML 功能?
- spring-boot - 用于在 Spring Boot JPA 中执行本机 SQL IN 子句查询的 SQLSyntaxErrorException
- centos - OpenLDAP 策略翻译
- javascript - 更改多个字体颜色
- bash - 将 linux 命令移动到 shell 脚本中
- django - ASGI vs WSGI,WSGI 兼容性问题
- pandas - 加入两个数据帧并使用数据帧的索引获取新帧
- zsh - oh-my-zsh:找不到插件“git-remote-branch”
- python - 通过分组使两个数组大小相同
- php - Laravel api 错误 405 方法不允许 + POST 方法被服务器接收为 GET