首页 > 解决方案 > 无法读取未定义的属性“小”

问题描述

当尝试从 API 访问作为图像 src 的链接时,我收到一条错误消息,指出该属性未定义。

以下是 API 中的项目示例,它们都具有相同的属性:

{
    "id": 1,
    "date": 1606311631,
    "title": "A Simple Guide to Design Thinking",
    "content": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.",
    "thumbnail": {
      "large": "https://images.unsplash.com/photo-1454692173233-f4f34c12adad?ixlib=rb-1.2.1&auto=format&fit=crop&w=1180&q=80",
      "small": "https://images.unsplash.com/photo-1454692173233-f4f34c12adad?ixlib=rb-1.2.1&auto=format&fit=crop&w=590&q=80"
    },
    "author": {
      "name": "John Doe",
      "avatar": "https://images.unsplash.com/photo-1492562080023-ab3db95bfbce?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&h=400&q=80",
      "role": "Product Owner"
    }
  },

现在,我映射了 json 中的所有项目,但是当我调用这个函数时:

const AppContainer = (props) => {
    return (
        <>
            {props.data.map((item) => (
                <ItemWrapper key={item.id} item={item} />
            ))}
        </>
    );
};

const ItemWrapper = (item) => {
    return (
        <>
            <img src={item.thumbnail.small} alt="" />
            <span className="blueDot"></span>
            <span className="yellowDot"></span>
            <div className="title">{item.title}</div>
            <div className="content">{item.content}</div>
            <div className="authorInfo">
                {item.author.name} - {item.author.role}
            </div>
            <div className="date">{item.date}</div>
        </>
    );
};

我收到“TypeError:无法读取未定义的属性‘小’”错误。它正在阅读item.thumbnail,但似乎无处可寻。我应该如何纠正这个?

标签: javascriptjsonreactjsapi

解决方案


你没有正确解构你的props对象:

const ItemWrapper = ({item})


推荐阅读