【发布时间】:2019-11-10 02:09:07
【问题描述】:
使用此代码:
const Products = () => {
const classes = useStyles();
const { data } = useFetch('/categories');
return (
<div className={classes.root}>
<GridList cellHeight={180} className={classes.gridList}>
<GridListTile key="Subheader" cols={6} style={{ height: 'auto' }} />
{data &&
data.map((category: CategoryInterface) => {
return (
<GridListTile key={category.id}>
<GridListTileBar title={category.name} />
</GridListTile>
);
})}
</GridList>
</div>
);
};
我在地图之前的数据上得到“对象可能为空”,我尝试使用 && 运算符来摆脱它,我还尝试定义像 const categories = data as CategoryInterface[] 这样的变量,但这表明我必须先转换为未知,我应该怎么做呢?
这里是 useFetch 钩子
import { useEffect, useState } from 'react';
export const useFetch = (url: string) => {
const [state, setState] = useState({ data: null, loading: true });
useEffect(() => {
setState(state => ({ data: state.data, loading: true }));
fetch(url)
.then(res => res.json())
.then(json => setState({ data: json, loading: false }));
}, [url, setState]);
return state;
};
【问题讨论】:
-
您的数据是什么样的?是数组吗?
-
我添加了代码,它的类型为 null
标签: reactjs typescript