如何使用新状态更新渲染

时间:2019-05-01 19:05:35

标签: arrays reactjs jsx

将新值插入到数组中有效,但是我希望在渲染器中更新表

[data-component='sidebar'] .first-menu {
  position: absolute;
  top: 60px; // 0 if you want it to start right at the top of left menu
  left: 0;
  height: 100%;
  background-color: #292a2c;
  width: 75px;
  overflow: hidden;
  transition: width 0.5s;
}
this.state = {
materials: [
                {
                    material: {id: 1, label: 'm1'},
                    quantity: 2,
                    unitPrice: 12,
                    total: 0
                },
                {
                    material:  {id: 2, label: 'm2'},
                    quantity: 4,
                    unitPrice: 15,
                    total: 1
                }
            ]
}

handleOnClick(e){
        this.state.materials.push(this.state.selectedMaterialUnitID, this.state.quantity, this.state.unitPrice, this.state.total);
        console.log(this.state.materials); // this worked fine

    }

预期结果是表更新并插入新行

2 个答案:

答案 0 :(得分:3)

反应不知道您已更新状态。

在使用react更新状态时,请使用this.setState(/* new value */)

您的代码应如下所示:

handleOnClick(e) {
  this.setState({
    // just materials. the other keys will not be affected.
    materials: [
      ...this.state.materials,
      this.state.selectedMaterialUnitID,
      this.state.quantity,
      this.state.unitPrice,
      this.state.total,
    ]
  });

  // this will show the old state now, since updating the state is asynchronous.
  console.log(this.state.materials);
}

如果希望console.log反映更新后的状态,则可以使用setState的第二个参数,如下所示:

handleOnClick(e) {
  this.setState({
    materials: [
      ...this.state.materials,
      this.state.selectedMaterialUnitID,
      this.state.quantity,
      this.state.unitPrice,
      this.state.total,
    ]
  },
  (state) => {
    console.log(state.materials);
  }
  );
}

我不确定您的.push方法将如何与所有这些额外参数一起使用,但是我希望您明白了。如果要向数组添加新对象,只需添加适当的定界符和键即可。

编辑以添加:检查为什么不应该直接更新状态的链接:https://reactjs.org/docs/state-and-lifecycle.html#do-not-modify-state-directly

答案 1 :(得分:1)

使用设置状态setState() tutorial

official docs

@GET("latest")
Call<CurrencyExchange> getCurrency();