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

标签 javascript reactjs eslint

我正在学习 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/

相关文章:

javascript - 向google.earth.createInstance()添加超时

javascript - 如何将 jquery 变量作为属性传递到输入中

reactjs - 使用React.lazy、Suspense 和react-router-dom 进行代码分割不起作用

javascript - Mobx 强制更新计算值

javascript - 如何仅解构数组的第一个索引

javascript - 在不修改数据存储的情况下将选项附加到组合框

javascript - 脚本可以在 Chrome 中运行,但不能在 Firefox 中运行

javascript - React 16 钩子(Hook)在嵌套 npm 包中不起作用

javascript - Prop 验证 react / Prop 类型错误中缺少“参数值”

javascript - Eslint 在 VScode 中不工作,但在终端工作