如何在Typescript的React setState中将项目添加到不可变数组?

问题描述 投票:0回答:1

我想使用不可变数组来处理状态。并将一个项目添加到此列表。

interface MainState {
  list: readonly []; // define immutable array
}

const Component: React.FC = () => {
  // by default use the immutable array with type
  const [classes, setClasses] = useState({ list: [] } as MainState);

  useEffect(() => {
    if (data) {
      data.forEach((thing) => {
        setClasses(prevState => {
          //
          // Call signature return types '{ list: never[]; }' and 'MainState' are incompatible.
          // The types of 'list.length' are incompatible between these types.
          // Type 'number' is not assignable to type '0'.  TS2345
          //
          const list = prevState.list.concat(thing);
          return { list };
        });
      });
    }
  });
// ...

}

尽管我使用concat也可以,因为它是returns a new array

reactjs typescript immutability
1个回答
1
投票

最简单,最容易接受的方式:

const list = [...prevState.list, thing];
© www.soinside.com 2019 - 2024. All rights reserved.