React update state数组对象的单个属性

时间:2018-01-18 16:10:24

标签: javascript reactjs

我有以下方法:

  addWidget = (index) => {
    var currentState = this.state;

    if(currentState.availableWidgets[index].pos === 'start'){

      // add it at the start
      for(var i = 0; i < currentState.widgets.length; i++){
        this.setState({
          widgets: [
            ...currentState.widgets,
            currentState.widgets.x = 5
          ]

        })
      }
    }
    else {
      var endX = currentState.widgets.reduce((endX, w) => endX + w.w, 0)
      if (endX === 12) endX = 0

      this.setState({
        widgets: currentState.widgets.concat({
          ...currentState.availableWidgets[index],
          i: uuid(),
          x: endX,
          y: Infinity,
        })
      })
    }

    console.log(currentState.widgets);
  }

状态是:

class DashboardContainer extends React.Component {
  state = {
    widgets: [],
    availableWidgets: [
      {
        type: 'compliance-stats',
        config: {

        },
        w: 1,
        h: 1,
        pos: 'start',
      },
      {
        type: 'compliance-stats',
        config: {

        },
        w: 3,
        h: 2,
      }
    ]
  }
  ...

我正在尝试更新&#34; x&#34;内部每个对象的属性&#34;小部件&#34;通过这样做:

  for(var i = 0; i < currentState.widgets.length; i++){
    this.setState({
      widgets: [
        ...currentState.widgets,
        currentState.widgets.x = 5
      ]

    })
  }

我知道在循环中设置状态并不好。但是我目前收到错误。

enter image description here

我正在导入小部件:

const Dashboard = ({ widgets, onLayoutChange, renderWidget }) => {
  const layouts = {
    lg: widgets,
  }

  return (
    <div>
      <ResponsiveReactGridLayout 
        layouts={layouts} 
        onLayoutChange={onLayoutChange} 
        cols={{ lg: 12 }} 
        breakpoints={{lg: 1200}}>
          {
            widgets.map(
              (widget) => 
              <div key={widget.i}>
                {renderWidget(widget)}
              </div>
            )
          }
      </ResponsiveReactGridLayout>
    </div>
  )
}

2 个答案:

答案 0 :(得分:3)

可能最好只更改一次widgets然后setState

const changedWidgets = currentState.widgets.map(w => ({ ...w, x: 5 }));
this.setState({ widgets: changedWidgets });

答案 1 :(得分:0)

数组中的扩展运算符会将一个新值连接到数组上,因此通过将小部件状态设置为[ ...currentState.widgets, currentState.widgets.x = 5 ],您实际尝试执行的操作是currentState.widgets.concate(currentState.widgets.x = 5),这会导致错误

如果你想修改数组中的值,你应该映射出数组,然后像这样修改数组中的对象。

const widgets = currentState.widgets.map(widget => { ...widget, x: 5})
this.setState({ widgets })