问题描述
问题
TypeError: Cannot read property 'id' of undefined
(anonymous function)
E:/Project-VidM/client/src/components/Blog/index.js:21
18 |
19 | const Articles = article.map((entry) => {
20 | return(
> 21 | <div className="entry" key={entry.sys.id}>
| ^ 22 | <h1>{entry.fields.title}</h1>
23 | <img src={entry.fields.featuredImage.sys} />
24 | {entry.fields.body.data}
View compiled
这是我的React代码
import React,{ useState,useEffect} from 'react'
import * as contentful from 'contentful';
const BlogComponent = () => {
const [article,setArticle] = useState([]);
const client = contentful.createClient({
space: 'xxxxxxxx',accesstoken: 'xxxxxxxxxxxxxxxxxxxxxxxx'
});
useEffect(() => {
client.getEntries()
.then((res) => {
setArticle([res.items]);
})
},[])
const Articles = article.map((entry) => {
return(
<div className="entry" key={entry.sys.id}>
<h1>{entry.fields.title}</h1>
<img src={entry.fields.featuredImage} />
{entry.fields.body.data}
</div>
)
})
return (
<div>
{Articles}
</div>
)
}
export default BlogComponent
在res.items
上执行console.log时,得到以下输出:
如何映射特定字段?
解决方法
在console.log res.items
中是一个数组,您将其放在另一个数组中
它应该是setArticle(res.items)
而不是setArticle([res.items])