我正在做一个关于React Hooks和获取数据的教程。这是我用来获取客户并将其映射到列表中的组件:
const useFetch = (url: string) => {
const [customers, setCustomers] = useState<null | []>(null);
const [loading, setLoading] = useState(true);
// Similiar to componentDidMount() and componentDidUpdate()
useEffect(() => {
const fetchData = async () => {
const result = await axios(url);
setCustomers(result.data);
setLoading(false);
};
fetchData();
});
return { customers, loading };
};
const url = 'https://jsonplaceholder.typicode.com/users';
export const LatestCustomers: React.FC<Props> = ({
description
}: Props): JSX.Element => {
const { customers, loading } = useFetch(url);
return (
<Container>
{loading ? (
<div>...Loading...</div>
) : (
<tr>
{customers.map(customer => (
<div key="user.id">{customer.name}</div>
))}
</tr>
)}
</Container>
);
};
有了这个,我得到了错误:
Object is possibly 'null'. TS2531
108 | ) : (
109 | <tr>
> 110 | {customers.map(customer => (
| ^
111 | <div key="user.id">{customer.name}</div>
112 | ))}
113 | </tr>
我该如何解决?
答案 0 :(得分:1)
由于提供给useState
的类型为null | []
,因此customers
被赋予了该类型签名。
有两种方法可以解决此问题。我的建议是从一个空数组开始:
const [customers, setCustomers] = useState<[]>([]);
或者,如果您希望保留可选类型,则应首先检查customers
不是null
:
{customers && customers.map(customer => ( ...
或者,如果您确实确定将始终对其进行定义,则可以使用TypeScript non-null assertio n !
运算符:
{customers!.map(customer => (
答案 1 :(得分:1)
处理可为空值的可靠解决方案可以是在fp-ts和fromNullable
中使用Option
https://github.com/gcanti/fp-ts/blob/master/src/Option.ts
示例:
{fromNullable(customers).map(x=> {...})}
有趣的文章: https://davetayls.me/blog/2018/05/20/fp-ts-01-working-with-nullable-values
其他更直接的方法:
{customers && customers.map(x => ( ...