【问题标题】:Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead错误:对象作为 React 子项无效(找到:[object Promise])。如果您打算渲染一组孩子,请改用数组
【发布时间】:2020-07-06 15:02:21
【问题描述】:

所以我正在学习 React 和非常基本的全栈 Web 开发,当我试图在我的 Mongodb 中获取一组对象时,我一直在兑现这个承诺。通过 Postman,我知道它正在返回我想要的 [{},{},...]。但是当我尝试在我的组件中使用它来映射我不断得到的名称时

Error: Objects are not valid as a React child (found: [object Promise]). If you meant to render a collection of children, use an array instead.

在我的 Web 控制台上,我的列表显示为 Promise,但其中包含我想要的数组。我一直在用我的承诺尝试不同的设置,就像这里的许多帖子所说的那样,以解决它,但我尝试过的一切都不会改变这个结果。

const ArticlesListPage = async () => {

    let testResult = function()
    {
        return fetch('/api/articles-list').then(result => {return result});
    };


    let results = testResult();
    results.then(function(res){
        console.log(res.json());
    })

}

export default ArticlesListPage;

还有组件:

const ArticlesList = ({articles}) => (

    <>
        {articles.map((article, key) => (
            <Link className="article-list-item" key={key} to={`/article/${article.name}`}>
                <h3>{article.title}</h3>
                <p>{article.content[0].substring(0,150)}...</p>
            </Link>
        ))}
    </>
);

export default ArticlesList;```

【问题讨论】:

  • .then(result =&gt; {return result}) - 听起来你正试图将异步结果转换为同步结果 - 你不能这样做
  • 当然,另一个问题是ArticlesListPage 返回一个解析为undefined 的 Promise - 因为您不会从该异步函数返回任何内容

标签: javascript reactjs mongodb promise es6-promise


【解决方案1】:

这是因为您返回的是 Promise,而 React Component 只能返回 JSX。有关详细信息,请参阅此问题:

Why does putting a div tag allow this React code to compile?

这是错误的部分,获取返回:

return fetch('/api/articles-list').then(result =&gt; {return result});

页面(因为是React Component)不能返回fetch

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 2021-09-28
    • 2021-12-10
    相关资源
    最近更新 更多