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

Cannot access the nested objects's data in render function using React useState

我想在页面上显示 user 对象的数据。最初,我有 使用 useStatecats 值设置为空数组 你可以在下面看到。

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:58e008450aac31001185ecfd

你可以试试这个: { cat.user && cat.user.name.first}