无法使用 React useState 在渲染函数中访问嵌套对象的数据



我想在页面上显示user对象的数据。最初,我使用CCD_ 3将CCD_你可以看到下面。

useEffect(() => {
fetchItems();
}, []);

const [cats, setcats] = useState([]);

const fetchItems = async () => {
const data = await fetch("https://cat-fact.herokuapp.com/facts/");
const cats = await data.json();
setcats(cats.all);
};

下面是我的渲染函数。

<div>
<h1>Shop Page</h1>
<hr />

{cats.map((cat) => (
<div key={cat._id}>
<strong>Id: </strong>{" "}
<Link to={`/Shop/${cat._id}`} style={linkstyle}>
{cat._id}
</Link>
<br />
<strong>Text: </strong> {cat.text}
<br />
<strong>Upvotes: </strong> {cat.upvotes}
<strong>UserName: </strong>
{cat.user.name.first}
{/* Above line is not working */}
<p>{JSON.stringify(cat.user)}</p>
{/* Above line actually prints the complete data in a cat objects's data including first name and last name */}
<hr />
</div>
))}
</div>

我得到以下错误。

TypeError: Cannot read property 'name' of undefined
(anonymous function)
E:/online study/learn_react/react-router/src/Shop.js:38
35 | <br />
36 | <strong>Upvotes: </strong> {cat.upvotes}
37 | <hr />
> 38 | <strong>UserName: </strong>
| ^  39 | {cat.user.name.first}
40 | {/* Above line is not working */}
41 | <p>{JSON.stringify(cat.user)}</p>

然而,JSON.stringify(cat.user)似乎工作良好,并显示页面上字符串格式的信息。

https://cat-fact.herokuapp.com/facts/的响应如下。

{
"all": [
{
"_id": "58e009550aac31001185ed12",
"text": "The oldest cat video on YouTube dates back to 1894.",
"type": "cat",
"user": {
"_id": "58e007480aac31001185ecef",
"name": {
"first": "Kasimir",
"last": "Schulz"
}
},
"upvotes": 6,
"userUpvoted": null
},
{
"_id": "58e008340aac31001185ecfb",
"text": "Cats sleep 70% of their lives.",
"type": "cat",
"user": {
"_id": "58e007480aac31001185ecef",
"name": {
"first": "Kasimir",
"last": "Schulz"
}
},
]
}

我不明白我犯的错误是什么,也不明白我的观点俯瞰。请帮我做这个。

提前感谢。

附件是一些屏幕截图供参考。

[1] :https://i.stack.imgur.com/rSNIn.png[2]:https://i.stack.imgur.com/EMVS1.png[3]:https://i.stack.imgur.com/lk05x.png

编辑

我从社区给出的答案中找到了解决方案。我的代码是正确的,但其中一个响应中似乎缺少user对象,我没有注意到,也没有过滤掉错误的响应,这导致了这个错误。

来自https://cat-fact.herokuapp.com/facts/的响应包括缺少user属性的cat

{
_id: "58e008450aac31001185ecfd", 
text: "A cat was mayor of Talkeetna, Alaska, for 20 years…His name is Stubbs, and he died on July 23, 2017.", 
type: "cat", 
upvotes: 1, 
userUpvoted: null
}

要么修复数据,要么过滤掉:

setcats(cats.all.filter(c => c.user));

用户属性不存在,此Id为:58e08450aac31001185ecfd

您可以尝试以下操作:{cat.user&&cat.user.name.first}

相关内容

  • 没有找到相关文章