反应:根据数组值设置状态

时间:2018-07-30 13:33:52

标签: javascript reactjs

我有一系列这样的问题

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

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

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

1 个答案:

答案 0 :(得分:7)

您可以使用reduce遍历数组,并将所有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);