pet*_*gan 2 typescript reactjs react-hooks
我从很多角度遇到了这个问题,目前我的代码看起来像这样,并且出现以下错误:
属性“相册”在“从不”类型上不存在
我正在使用React挂钩,但是从中data更新了的对象出现了错误useState。我不确定如何定义data属性albums或在何处执行此操作。
import React, { useState } from 'react';
interface ArtistProps {
artistName: string,
}
const Artist: React.SFC< ArtistProps > = ({ artistName }) => {
const [data, setData] = useState(null);
return (
<>
<p>{artistName)}</p> // this is fine
<p>{data.albums}</p> // error here
</>
);
}
Run Code Online (Sandbox Code Playgroud)
尝试这个:
const [data, setData] = useState<null | {albums: any}>(null);
Run Code Online (Sandbox Code Playgroud)
然后data像这样使用变量
data!.albums
Run Code Online (Sandbox Code Playgroud)
该!是让打字稿知道你肯定值不null。但更好的方法是显式检查该值,null例如data ? data.albums : 'no data'
PS而不是{albums: any}添加您适当的界面。
| 归档时间: |
|
| 查看次数: |
2360 次 |
| 最近记录: |