using update immutablity helper I get eslint error : Use callback in setState when referencing the previous state

using update immutablity helper I get eslint error : Use callback in setState when referencing the previous state

提前致谢。我使用 immutability - helper 来设置状态。但是我在 this.setState 附近收到 eslint 错误 它说:Use callback in setState when referencing the previous state 自从我使用 immutablity helper 以来有什么解决方法吗我需要使用 prevState 任何人都可以分享更正的方法。

import update from 'immutability-helper';

moveSection = (dragIndex, hoverIndex) => {
    const { list} = this.state;
    const dragCard = list[dragIndex];

    this.setState(
      update(this.state, {
        list: {
          $splice: [
            [dragIndex, 1],
            [hoverIndex, 0, dragCard],
          ],
        },
      }),
    ); };

试试这个:

this.setState(
  (state) => {
     return update(state, {
       list: {
         $splice: [
           [dragIndex, 1],
           [hoverIndex, 0, dragCard],
         ],
       },
     })
  }
);

它告诉你这样做:

this.setState(prevState => 
  update(prevState, {
    list: {
      $splice: [
        [dragIndex, 1],
        [hoverIndex, 0, dragCard],
      ],
    },
  }),
);

如果状态快速连续更改多次,React 可能会批量处理这些更改并将它们全部应用到单个渲染中。因此,如果您调用 update 并传入 this.state,则无法保证 this.state 具有最新状态,因此您最终可能会丢弃由另一个状态更新。

如果您改为使用 setState 的函数版本,那么您 可以保证获得最新的状态,并且消除了这个可能的错误。