setState():不直接改变状态。使用setState()

时间:2019-02-16 16:07:09

标签: javascript reactjs

我在运行代码时收到以下警告:

  

第48行:请勿直接更改状态。使用setState()   反应/无直接突变状态

此警告涉及以下代码行:

updateDelay(prediction_arr,prediction_dep) {
  this.state.chartDataWake = [...this.state.chartDataWake, {wake: this.state.wake===84.73 ? "H" : (this.state.wake===14.78 ? "M" : "L"), delay: prediction_arr}];
  this.state.chartDataTurnaround = [...this.state.chartDataTurnaround, {turnaround: this.state.schedTurnd, delay: prediction_arr}];

  this.setState({
    prediction_arr: prediction_arr,
    prediction_dep: prediction_dep,
    delay_arr_cat: prediction_arr===0 ? "<15" : (prediction_arr===1 ? "[15; 45]" : ">45")
  });
};

我知道我应该将所有声明放在this.setState({中。但是我不清楚应该如何准确地更改

this.state.chartDataTurnaround = [...this.state.chartDataTurnaround, {turnaround: this.state.schedTurnd, delay: prediction_arr}];

以便能够编译代码。

3 个答案:

答案 0 :(得分:3)

1-不要直接使用setState来更改状态,因此请删除前两行。

2-因为setState is async和您正在基于先前的值更新状态,所以使用updater function意味着在setState中传递一个函数,并在该函数中使用prevState值。

>

赞:

updateDelay(prediction_arr,prediction_dep) {
  this.setState(prevState => ({
    prediction_arr: prediction_arr,
    prediction_dep: prediction_dep,
    delay_arr_cat: prediction_arr===0 ? "<15" : (prediction_arr===1 ? "[15; 45]" : ">45"),

    chartDataWake: [
      ...prevState.chartDataWake,
      {wake: prevState.wake===84.73 ? "H" : (prevState.wake===14.78 ? "M" : "L"), delay: prediction_arr}
    ],

    chartDataTurnaround: [
      ...prevState.chartDataTurnaround,
      {turnaround: prevState.schedTurnd, delay: prediction_arr}
    ]
  }));
};

答案 1 :(得分:2)

请勿使用this.state.YOUR_VARIABLE = something

修改状态

如果您愿意,并且从摘要中可以看到, 要将prevState复制到新状态并能够向其添加新元素,则应使用对象克隆功能先复制先前的状态,然后再向该副本添加更多的元素。

updateDelay(prediction_arr, prediction_dep) {
 const newChartDataWake = [...this.state.chartDataWake, {
  wake: this.state.wake === 84.73 ? "H" : (this.state.wake === 14.78 ? "M" : "L"),
  delay: prediction_arr
 }];

 const newChartDataTurnaround = [...prevState.chartDataTurnaround, {
  turnaround: prevState.schedTurnd,
  delay: prediction_arr
 }]



 this.setState(prevState => {
  return {
   chartDataWake: newChartDataWake
   chartDataTurnaround: newChartDataTurnaround
   prediction_arr: prediction_arr,
   prediction_dep: prediction_dep,
   delay_arr_cat: prediction_arr === 0 ? "<15" : (prediction_arr === 1 ? "[15; 45]" : ">45")
  }
 });
};

答案 2 :(得分:2)

您应该对setState使用回调,该回调将以前的State作为参数。

this.setState((prevState,props) => 
({
   chartDataWake:[...prevState.chartDataWake, {wake: prevState.wake===84.73 
       ? "H" : (prevState.wake===14.78 ? "M" : "L"), delay: prediction_arr}],
   chartDataTurnaround = [...prevState.chartDataTurnaround, {turnaround: 
      prevState.schedTurnd, delay: prediction_arr}],
   prediction_arr: prediction_arr,
   prediction_dep: prediction_dep,
   delay_arr_cat: prediction_arr===0 ? "<15" : (prediction_arr===1 ? "[15; 
      45]" : ">45")
})