未捕获的类型错误:无法读取未定义的属性(读取“map”)-Firestore API
2022-04-03
1491
我正在使用 react-admin 从 Firestore API 中获取以下格式的数据:
{
"documents": [
{
"name": "",
"fields": {
"teacher": {
"stringValue": ""
},
"slot": {
"stringValue": ""
},
"student_name": {
"stringValue": ""
}
},
"createTime": "2022-03-27T09:49:24.044423Z",
"updateTime": "2022-03-29T13:50:41.264007Z"
},
{
"name": "",
"fields": {
"teacher": {
"stringValue": ""
},
"slot": {
"stringValue": ""
},
"student_name": {
"stringValue": ""
}
},
"createTime": "2022-03-27T09:49:24.044423Z",
"updateTime": "2022-03-29T13:50:41.264007Z"
},
{
"name": "",
"fields": {
"teacher": {
"stringValue": ""
},
"slot": {
"stringValue": ""
},
"student_name": {
"stringValue": ""
}
},
"createTime": "2022-03-27T09:49:24.044423Z",
"updateTime": "2022-03-29T13:50:41.264007Z"
}
]
}
但是,当我尝试从这样的数据中提取某些字段时,
const List = () => {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("MY API URL")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name}
</li>
))}
</ul>
);
}
我收到以下错误: 未捕获的 TypeError:无法读取未定义的属性(读取“map”)
我找到了类似的答案,包括这里的答案: TypeError:无法读取未定义的属性(读取“map”)Table.render
但仍然无法弄清楚。任何帮助都会很棒,谢谢!
1个回答
您可以在您的项目中尝试可选链接(?。)。
{items?.map(item => (
<li key={item.id}>
{item.name}
</li>
))}
这应该可以防止出现错误。
另一件重要的事情是,您从
fetch
请求中返回的
result
可能是
undefined
并会引发 TypeError。
angel_dust
2022-04-04