admin管理员组文章数量:1288087
I'm learning React and I have ESLint installed in my project. It started giving me errors like:
Use callback in setState when referencing the previous state react/no-access-state-in-setstate
In my React ponent I have a constructor:
constructor() {
super()
this.state = {
currentIdVehicle: null,
currentIdModel: null,
currentIdVehicleFinal: null,
marca: [],
veiculo: [],
modeloEAno: [],
vehicleFinal: [],
infoTable: [],
};
}
In my function I have:
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 });
});
});
};
I understand that it is not correct to use this.state
within setState
, but how can I resolve this error?
I'm learning React and I have ESLint installed in my project. It started giving me errors like:
Use callback in setState when referencing the previous state react/no-access-state-in-setstate
In my React ponent I have a constructor:
constructor() {
super()
this.state = {
currentIdVehicle: null,
currentIdModel: null,
currentIdVehicleFinal: null,
marca: [],
veiculo: [],
modeloEAno: [],
vehicleFinal: [],
infoTable: [],
};
}
In my function I have:
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 });
});
});
};
I understand that it is not correct to use this.state
within setState
, but how can I resolve this error?
2 Answers
Reset to default 9Instead of this:
res.data.map((item) => {
const joined = this.state.marca.concat([
{ name: item.name, id: item.id },
]);
this.setState({ marca: joined });
});
Do this:
res.data.map((item) => this.setState(prevState => {
const joined = prevState.marca.concat([
{ name: item.name, id: item.id },
]);
return({ marca: joined });
}));
You're not supposed to directly or indirectly reference this.state
in what you eventually pass to this.setState
.
If you have to mutate the state (e.g. adding an item) then you can pass a function to setState
that receives the previous and returns the next state:
this.setState(previousState => ({ marca: [...previousState.marca, { name: item.name, id: item.id }] }));
It will be way faster to add all items at once though:
this.setState(previousState => ({
marca: [
...previousState.marca,
...res.data.map((item) => ({ name: item.name, id: item.id }))
],
}));
版权声明:本文标题:javascript - Why do I get "Use callback in setState when referencing the previous state"? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741318628a2372072.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论