反应挂钩和打字稿 - 属性 '***' 在类型 'never' 上不存在
react hooks and typescript - Property '***' does not exist on type 'never'
我从很多角度遇到过这个问题,目前我的代码看起来像这样,但我得到以下错误:
Property 'albums' does not exist on type 'never'
我正在使用 React 挂钩,但从使用 useState
更新的 data
对象中收到错误。 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
</>
);
}
试试这个:
const [data, setData] = useState<null | {albums: any}>(null);
然后像
一样使用data
变量
data!.albums
!
是为了让打字稿知道你确定这个值不是null
。但更好的是明确检查 null
的值,例如data ? data.albums : 'no data'
P.S。而不是 {albums: any}
添加适当的接口。
我从很多角度遇到过这个问题,目前我的代码看起来像这样,但我得到以下错误:
Property 'albums' does not exist on type 'never'
我正在使用 React 挂钩,但从使用 useState
更新的 data
对象中收到错误。 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
</>
);
}
试试这个:
const [data, setData] = useState<null | {albums: any}>(null);
然后像
一样使用data
变量
data!.albums
!
是为了让打字稿知道你确定这个值不是null
。但更好的是明确检查 null
的值,例如data ? data.albums : 'no data'
P.S。而不是 {albums: any}
添加适当的接口。