【问题标题】:Error while mapping fetched objects with ReactJs使用 ReactJs 映射获取的对象时出错
【发布时间】:2020-10-20 01:06:26
【问题描述】:

问题

我想从 contentflow 中获取文章,但这是我遇到的错误

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

这是我的反应代码

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 时,我得到以下输出:

如何映射特定字段?

【问题讨论】:

    标签: javascript reactjs contentful


    【解决方案1】:

    在console.log 中res.items 是一个数组,您将它放在另一个数组中

    应该是setArticle(res.items) 而不是setArticle([res.items])

    【讨论】:

    • 谢谢,但这样做会给我以下错误:``` 对象作为反应子项无效(找到:带键的对象 {})。如果您打算渲染一组孩子,请改用数组。 ```
    • entry.fields.body.data里面有什么?看起来它是一个对象而不是字符串或数字@SubhankarChowdhury
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-16
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多