如何使用useState钩子和Typescript初始化状态

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

状态将在将来的某个时候使用useState钩子与对象数组进行更新,该对象具有如下所示的接口:

export interface DataSource {
  dataPiont: Array<DataPoint>;
}

export interface DataPoint {
  [key: string]: string | number;
}

我在必须初始化状态的地方设置了钩子:

const [fetchedData, setFetchedData] = useState<DataSource>([{ key: '' }]);

但是我收到打字稿错误"Argument of type '{ key: string; }[]' is not assignable to parameter of type 'DataSource | (() => DataSource)'.

我不想在界面中添加nullundefined[],因为我必须在整个应用程序中使用它。

如何在这种情况下成功初始化状态?

非常感谢!

reactjs typescript react-hooks
1个回答
0
投票
因为DataSource具有dataPiont对象键。也许您想使用接口Array<DataPoint>来表示状态?

const [fetchedData, setFetchedData] = useState<Array<DataPoint>>([]);

© www.soinside.com 2019 - 2024. All rights reserved.