reactjs - 如何使用扩展运算符在循环中设置状态()
问题描述
我正在尝试使用循环中的扩展运算符为嵌套对象中的多个字段设置新值,但它仅适用于最后一个字段。
我有一个数组“formFields”,其中包含我想要覆盖的值的字段名称。我使用 map() 将数组中的每个元素与状态中的字段进行比较,并将其值切换为“true”。但它仅更改数组中最后一个字段的值 - “评论”。
constructor() {
super();
this.state = {
fields: {
time: false,
date: false,
quantity: false,
comment: false,
},
}
}
getFormFields() {
const formFields = ["time", "quantity", "comment"];
formFields.map(item => {
this.setState({
...this.state.fields,
[item]: true
})
});
}
我应该怎么做才能覆盖我想要的所有字段的值?
解决方案
由于您正在循环更改状态,并且您设置的每个状态都包含仅更改的原始项目,因此最新更改会覆盖前一个更改。相反,使用更改创建一个新的状态对象,然后 setState 对象一次:
getFormFields() {
const formFields = ["time", "quantity", "comment"];
this.setState(formFields.reduce((r, item) => ({
...r,
[item]: true
}), {}));
}
顺便说一句 - 如果您要设置的字段true
始终相同,您可以手动创建对象并设置它:
getFormFields() {
this.setState({
time: true,
quantity: true,
comment: true,
});
}
推荐阅读
- java - 在java中使用jetty发送一个json对象
- c# - 在等待响应时尝试在循环中使用延迟
- c# - JSONRpc Client over websocket C#
- clearcase - 如何知道 Clearcase 服务器视图是什么?
- html - CSS 和 HTML 4.0 错误导致富文本方法(QT)中的空格
- android - 计时器不会覆盖基准值
- php - Laravel 和本地化:如何在不同国家处理相同的语言?
- javascript - 使用上传按钮上传图片
- security - 查询字符串中的身份验证令牌是简单获取请求的唯一解决方案吗?
- ruby-on-rails - Rake 任务中的 SQL 执行时间