【发布时间】:2021-10-26 11:38:48
【问题描述】:
我尝试创建生成随机报价的简单应用程序。 我创建了一个函数(我认为)从 json 文件中获取我想要的数据。但是当我尝试将该函数传递给我的 App 函数时,我得到错误:对象作为 React 子对象无效(找到:[object Promise])
功能引用:
function Quote (data) {
var x = (Math.floor(Math.random() * (103 - 1) + 1) );
return fetch('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson['quotes'][0]['author']);
return responseJson['quotes'][x]['author'];
})
.catch((error) => {
console.error(error);
});
}
应用功能:
function App() {
var text = '';
return (
<div id="quote-box">
<div id="author"><Quote /></div>
<button id="new-quote">New Quote</button>
<a href="twitter.com" id="tweet-quote">Tweet</a>
</div>
);
}
【问题讨论】:
-
您的
Quote不是React组件。这是一个返回承诺的函数。我认为您需要阅读文档here 以更好地了解 React 组件的工作原理。
标签: javascript reactjs json