首页 > 解决方案 > React:根据数组值设置状态

问题描述

我有很多这样的问题

[
  {
    title: 'what_are_your_hobbies',
  },
  {
    title: 'do_you_know_german',
  },
]

我如何遍历这个数组并将其标题设置为如下状态:

state = {
  what_are_your_hobbies: '',
  do_you_know_german: ''
}

标签: javascriptreactjs

解决方案


您可以使用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);

推荐阅读