简体   繁体   English

尝试在 React 中使用 map 子对象时出现未定义错误

[英]Undefined error when trying to map child objects in React

I'm trying to get image url for nested JSON object.我正在尝试获取嵌套 JSON object 的图像 url。

Tried {post.image.url} but I get an error saying url undefined试过{post.image.url}但我收到一条错误消息,提示 url undefined

I appreciate any help or guidance that could be offered.我感谢可以提供的任何帮助或指导。 New to Javascript / React but after an hour of Googling and searching couldn't come up with a solution for this. Javascript / React 的新手,但经过一个小时的谷歌搜索和搜索后无法找到解决方案。 Must be missing something simple:-P必须缺少一些简单的东西:-P

Here's my code...这是我的代码...

export const getAllPosts = async () => {
    return await fetch(
        `https://notion-api.splitbee.io/v1/table/${NOTION_BLOG_ID}`
    ).then((res) => res.json());
}
export async function getStaticProps() {
    const posts = await getAllPosts()
    return {
        props: {
            posts
        },
    };
}
function Blog({ posts }) {
    return (
        <div>
            {posts.map((post) => (
                <Link href="/blog/[slug]" as={`/blog/${post.slug}`}>
                    <div>
                        <div className='text-6xl'>{post.title}</div>
                        <img className='w-24' src={post.imgUrl}></img>

                        
                        {/*{post.image.rawUrl}*/}

                    </div>
                </Link>
            ))}
        </div>
    );
}
export default Blog

Here's the JSON...这是 JSON...

[
{
"id": "90ee0723-aeb5-4d64-a970-332aa8f819f6",
"slug": "first-post",
"date": "2020-04-21",
"Related to Notion API Worker (Column)": [
"0976bfa6-392a-40b0-8415-94a006dba8d9"
],
"imgUrl": "https://www.notion.so/image/https:%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F689883de-2434-4be3-8179-a8ba62a7bc1e%2Fsnowmountain.jpg?table=block&id=90ee0723-aeb5-4d64-a970-332aa8f819f6&cache=v2",
"image": [
{
"name": "snowmountain.jpg",
"url": "https://www.notion.so/image/https:%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F689883de-2434-4be3-8179-a8ba62a7bc1e%2Fsnowmountain.jpg?table=block&id=90ee0723-aeb5-4d64-a970-332aa8f819f6&cache=v2",
"rawUrl": "https://s3-us-west-2.amazonaws.com/secure.notion-static.com/689883de-2434-4be3-8179-a8ba62a7bc1e/snowmountain.jpg"
}
],
"title": "My first blogpost bruce"
}
]

There is no need to call then() method, if you use async\await .如果您使用async\await ,则无需调用then()方法。

As mdn says: 正如 mdn 所说:

await can be put in front of any async promise-based function to pause your code on that line until the promise fulfills, then return the resulting value. await 可以放在任何基于异步承诺的 function 前面,以暂停该行上的代码,直到 promise 完成,然后返回结果值。

export const getAllPosts = async () => {
    return await fetch(
        `https://notion-api.splitbee.io/v1/table/${NOTION_BLOG_ID}`
    );
}

export async function getStaticProps() {
    const posts = await getAllPosts()
    return {
        props: {
            posts
        },
    };
}

The image property of a post is an array as denoted by the bracket on the end of line 1: postimage属性是一个数组,由第 1 行末尾的括号表示:

1. "image": [
2.   {
3.     "name": "snowmountain.jpg",
4.     "url": "https://www.notion.so/image/https:%2F%2Fs3-us-west-2.amazonaws.com%2Fsecure.notion-static.com%2F689883de-2434-4be3-8179-a8ba62a7bc1e%2Fsnowmountain.jpg?table=block&id=90ee0723-aeb5-4d64-a970-332aa8f819f6&cache=v2",
5.     "rawUrl": "https://s3-us-west-2.amazonaws.com/secure.notion-static.com/689883de-2434-4be3-8179-a8ba62a7bc1e/snowmountain.jpg"
6.   }
7. ],

If you know that there will always be exactly one image you could access it directly by referencing the first array item.如果您知道总会有一个图像,您可以通过引用第一个数组项直接访问它。

function Blog({ posts }) {
    return (
        <div>
            {posts.map((post) => (
                <Link href="/blog/[slug]" as={`/blog/${post.slug}`}>
                    <div>
                        <div className='text-6xl'>{post.title}</div>
                        <img className='w-24' src={post.imgUrl}></img>

                        
                        {post.image && post.image[0].rawUrl}

                    </div>
                </Link>
            ))}
        </div>
    );
}

Note that this could err if the array is undefined / null or if it's empty, so you should probably safe-guard it by only displaying something if it exists.请注意,如果数组undefined / null或它为空,这可能会出错,因此您可能应该通过仅显示存在的内容来保护它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试响应 MAP 数据时出现错误。 对象作为 React 子对象无效(找到:object 和键 {children}),我该如何解决? - I AM HAVING ERROR WHEN TRYING TO MAP A DATA IN REACT . Objects are not valid as a React child (found: object with keys {children}), How do i solve it? 反应:尝试 map 时,嵌套数组显示为未定义 - React: Nested Array shows as undefined when trying to map 尝试使用数组 map function 时反应属性未定义 - React property is undefined when trying to use array map function 尝试按索引访问 Map 的数组值时出现未定义错误 - Undefined error when trying to access Array value of Map by index 在反应中跳过 map 数组中的未定义对象 - skip undefined objects from a map array in react 将对象数组传递给在迭代中渲染的子组件会在 React 中返回未定义的错误 - Passing an array of objects to child component rendered within iteration returns undefined error in React 面对错误:即使在 ReactJS 中使用 map function 时,对象作为 React 子代也无效 - Facing Error: Objects are not valid as a React child even though using .map function in ReactJS 错误:对象作为 React 子项无效 - 错误位置? - Error: Objects are not valid as a React child - Location of Error? 对象在Datatable中作为React子错误无效 - Objects are not valid as a React child error in Datatable 如何处理错误:对象作为 React 子对象无效? - How to handle Error: Objects are not valid as React child?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM