javascript - React:根据数组值设置状态
问题描述
我有很多这样的问题
[
{
title: 'what_are_your_hobbies',
},
{
title: 'do_you_know_german',
},
]
我如何遍历这个数组并将其标题设置为如下状态:
state = {
what_are_your_hobbies: '',
do_you_know_german: ''
}
解决方案
您可以使用reduce
迭代数组并将 all 设置title
为新对象上的键并使用它来更新您的状态。
例子
const arr = [
{
title: "what_are_your_hobbies"
},
{
title: "do_you_know_german"
}
];
const stateUpdate = arr.reduce((result, element) => {
result[element.title] = "";
return result;
}, {});
this.setState(stateUpdate);
推荐阅读
- github - 验证 GitHub 变基和合并的提交消息
- r - 如何仅使用部分数字变量在 geom_tile ggplot 中对图块进行排序
- php - 通过 PHP 从端点返回“null”
- node.js - 如何使用 graphql 和 mongoose 进行突变
- r - 如何将标签添加到多个 ggplot 图(A、B、C)
- elasticsearch - 如何在 kafka-connect 融合平台的 elasticsearch sink 连接器配置中使用 ca cert?
- apache-spark - 编写数据帧时从 Spark 到数据库的连接有多少?
- python - 用户输入问题
- visual-studio-code - 在VScode中,如何在launch.json中添加带有$的参数
- pyodbc - 如何使用 pyodbc 接口连接计算表