我试图为嵌套的JSON对象获取图像url。
尝试了{post.image.url},但是我看到了一个错误:url未定义的
我很感激能提供的任何帮助或指导。新的Javascript / React,但经过一个小时的谷歌搜索和搜索无法找到解决方案。一定是错过了一些简单的东西:-P
这是我的密码。
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这是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"
}
]发布于 2021-03-02 08:29:09
image属性的post是一个数组,由第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. ],如果您知道始终只有一个映像,则可以通过引用第一个数组项直接访问它。
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>
);
}请注意,如果数组是undefined / null或者是空的,这可能会出错,因此您可能应该只在存在的情况下显示某些内容,从而安全地保护它。
发布于 2021-03-02 08:21:04
如果使用then(),则不需要调用async\await方法。
“等待”可以放在任何基于异步承诺的函数前面,以便在该行上暂停您的代码,直到承诺实现为止,然后返回结果值。
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
},
};
}https://stackoverflow.com/questions/66435594
复制相似问题