gpt4 book ai didi

javascript - 为什么我得到 "Use callback in setState when referencing the previous state"?

转载 作者:行者123 更新时间:2023-11-29 16:31:18 24 4
gpt4 key购买 nike

我正在学习 React,并且在我的项目中安装了 ESLint。它开始给我这样的错误:

Use callback in setState when referencing the previous state react/no-access-state-in-setstate

在我的 React 组件中,我有一个构造函数:

  constructor() {
super()
this.state = {
currentIdVehicle: null,
currentIdModel: null,
currentIdVehicleFinal: null,
marca: [],
veiculo: [],
modeloEAno: [],
vehicleFinal: [],
infoTable: [],
};
}

在我的函数中我有:

  getMarca = () => {
this.setState({ marca: [], veiculo: [], modeloEAno: [] });
api.get(`/marcas.json`).then(res => {
res.data.map((item) => {
const joined = this.state.marca.concat([
{ name: item.name, id: item.id },
]);
this.setState({ marca: joined });
});
});
};

我知道在 setState 中使用 this.state 是不正确的,但是我该如何解决这个错误?

最佳答案

取而代之的是:

      res.data.map((item) => {
const joined = this.state.marca.concat([
{ name: item.name, id: item.id },
]);
this.setState({ marca: joined });
});

这样做:

      res.data.map((item) => this.setState(prevState => {
const joined = prevState.marca.concat([
{ name: item.name, id: item.id },
]);
return({ marca: joined });
}));

您不应该在最终传递给 this.setState 的内容中直接或间接引用 this.state

关于javascript - 为什么我得到 "Use callback in setState when referencing the previous state"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56717633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com