运行代码时会收到以下警告:
第48行:不要直接改变状态。使用setState() react/无直接突变状态
此警告引用以下代码行:
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}];以便能够编译代码。
发布于 2019-02-16 16:15:41
不要直接改变状态,请使用setState,所以删除前两行。
2-因为setState是异步的和您正在根据以前的值更新状态,所以使用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}
]
}));
};发布于 2019-02-16 16:15:41
永远不要使用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")
}
});
};发布于 2019-02-16 16:19:29
您应该使用setState的回调,它将前一个状态作为参数。
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")
})https://stackoverflow.com/questions/54724995
复制相似问题