我想使用不可变数组来处理状态。并将一个项目添加到此列表。
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。
最简单,最容易接受的方式:
const list = [...prevState.list, thing];