【问题标题】:Push predefined objects into array using setState in react在 react 中使用 setState 将预定义的对象推送到数组中
【发布时间】:2019-02-04 11:52:29
【问题描述】:

如何使用扩展运算符/ES6 实现这一点?

我想遍历我的数据并使用包含两个键/值对的对象数组填充我的状态。我希望它像...

this.state = {
data: [ {indexNumber: 1, show: false}, {indexNumber: 2, show: false}, {indexNumber: 3, show: false} ]

我的[变异]版本;

this.state = { data: []}

data.map((element, index) => {
    this.state.data.push({ indexNumber: index, show: false}] })
});

【问题讨论】:

    标签: javascript arrays reactjs immutability setstate


    【解决方案1】:

    您不能修改状态对象。您必须调用 setState 并使用新值:

    this.setState({data: [...this.state.data, {indexNumber: index, show: false}]})

    【讨论】:

      猜你喜欢
      • 2021-01-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-06
      • 1970-01-01
      • 2018-09-03
      • 2020-08-10
      • 1970-01-01
      相关资源
      最近更新 更多