JSON数组上的“从不”类型不存在属性
Posted
技术标签:
【中文标题】JSON数组上的“从不”类型不存在属性【英文标题】:Property does not exist on type 'never' on JSON array 【发布时间】:2021-05-18 03:39:49 【问题描述】:我只是想从一个 url 获取一些 JSON 数据。 JSON 数据的格式如下(为简单起见减少为两个条目):
[
"id": 1
"name": "Brett",
"gender": "male"
,
"id": 2
"name": "Sandra",
"gender": "female"
]
我可以使用console.log(profiles)
打印profiles
并查看控制台中的所有条目,但是当我尝试访问 .name 字段时出现错误
Property 'name' does not exist on type 'never'.
这是应用程序的代码:
const URL = 'someurl'
function App()
const [curId, setId] = useState(0);
//const [curProfile, setCurProfile] = useState(undefined);
const [profiles, setProfiles] = useState([])
useEffect(() =>
fetch(URL)
.then((response) =>
if (response.ok)
return response.json();
else
throw new Error("Something went wrong!");
)
.then(
(response) =>
setProfiles(response);
setId(1);
//setCurProfile(profiles[curId - 1]);
)
.catch((error) =>
console.log(error)
)
, []);
return (
<div className="App">
<p>
profiles[curId].name
</p>
</div>
);
export default App;
另外作为一个附带问题,我在将当前配置文件存储在 curProfile 变量中时遇到了一些问题。有人可以为我指出正确的方向吗?谢谢!
【问题讨论】:
【参考方案1】:profiles
的初始状态为空数组,curId
为 0,所以 profiles[curId]
应该是未定义的,因此 profiles[curId].name
在初始渲染时会出错。
您应该始终检查profiles
是否为空。
return (
<div className="App">
profiles.length > 0 &&
<p>
profiles[curId].name
</p>
</div>
)
【讨论】:
【参考方案2】:你必须输入你的状态,否则 Typescript 将不知道会发生什么。您还需要输入响应。
类似:
type Profile =
id: number,
name: string,
gender: string
const [profiles, setProfiles] = useState <Profile[]> ([]);
(...)
setProfiles(response as Profile[]);
【讨论】:
以上是关于JSON数组上的“从不”类型不存在属性的主要内容,如果未能解决你的问题,请参考以下文章
如何更新 json 类型的 json 中的任何字段?它应该接受一个对象或一个键数组,如果它存在则更新键,否则创建
检查 JSON 数组中是不是存在值,如果不存在则检查下一个数组(Swift / SwiftUI)