运行代码时出现以下警告:
第48行:不要直接改变状态。使用setState()react / no-direct-mutation-state
此警告涉及以下代码行:
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}];
为了能够编译代码。
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}
]
}));
};
切勿使用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")
}
});
};
您应该使用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")
})