【发布时间】:2021-11-11 18:05:00
【问题描述】:
核心问题 - 我在哪里搞砸了我的 useState
const [data, setData] = useState<IAssetGetManyResponseDto<IAssetResponseDto>>();
所以我作为道具发送的data对象是undefined?
我的(正常运行的)api 调用如下所示
export const getAllAssets = async (
): Promise<IAssetGetManyResponseDto<IAssetResponseDto>> => {
console.log("get all assets ran in api.ts!")
const response = await amsApiClient.get(ASSET_ENDPOINT(),
{
params: {
limit: 1000
}
}
);
console.log("logging response data "+JSON.stringify(response.data))
return response.data;
};
这里是使用的类型:
export interface IAssetGetManyResponseDto<T> {
items: T[];
totalCount: number;
}
export interface IAssetResponseDto {
id: string | null;
name: string | null;
type: string | null;
url: string | null;
// metadata: IMetadataObj| null;
tags: Array<string> | null;
thumbnailImageURL: string | null;
createdAt: number | null;
updatedAt: number | null;
}
这是进行调用的组件,以显示上下文
export const AssetManagementTable = () => {
const [data, setData] = useState<IAssetGetManyResponseDto<IAssetResponseDto>>();
const getAssets = async () => {
console.log("getAssets ran!")
const assets = await getAllAssets();
console.log("logging data from asset managment table " + data)
console.log("logging assets from asset managment table " + assets)
setData(assets)
}
useEffect(() => {
getAssets()
}, []);
return (
<div>
<NewAssetTable items={data} />
</div>
);
};
在我的应用程序的其他地方,当我向下传递道具并引用props.items.map((item: any). => {... 时,我得到了undefined。
更具体地说,TypeError: Cannot read properties of undefined (reading 'map')
我是否通过不正确地指定类型而弄乱了 useState 的参数?
谢谢!
【问题讨论】:
标签: reactjs typescript generics use-effect use-state