【发布时间】: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 => {return result})- 听起来你正试图将异步结果转换为同步结果 - 你不能这样做 -
当然,另一个问题是
ArticlesListPage返回一个解析为undefined的 Promise - 因为您不会从该异步函数返回任何内容
标签: javascript reactjs mongodb promise es6-promise