javascript - 如何在 React 中显示来自 json 的数据
问题描述
我尝试创建生成随机报价的简单应用程序。我创建了一个函数(我认为)从 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>
);
}
解决方案
我会使用 useEffect 在开始时触发呼叫。并使用 useState 保存该值。然后还将相同的逻辑添加到 onClick 中。
import { useEffect, useState } from "react";
function getQuote() {
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);
});
}
export default function App() {
const [author, setAuthor] = useState("");
useEffect(() => {
getQuote().then((newAuthor) => setAuthor(newAuthor));
}, []);
return (
<div id="quote-box">
<div id="author">{author}</div>
<button
id="new-quote"
onClick={() => getQuote().then((newAuthor) => setAuthor(newAuthor))}
>
New Quote
</button>
<a href="twitter.com" id="tweet-quote">
Tweet
</a>
</div>
)
}
推荐阅读
- c++ - 在 C++ 中使用“DEFINED”子表达式组合复杂的正则表达式
- c# - 如何在另一个场景中引用对象的组件?
- python - AWS lambda UnicodeDecodeError
- swift - 使用 typealias 从回调转移到委托
- kubernetes - Kubernetes 服务将外部 ip 设置为待处理
- javascript - 有没有办法计算 discord.js 中提及的字符
- javascript - Html 联系表单按钮处于非活动状态
- xamarin - 如何在 Xamarin 表单中针对不同环境在 android 和 iOS 项目上配置 APP CENTER 应用程序密钥?
- python - 如何在 Pyspark 中使用 groupby 删除列
- javascript - 当我播放我的 3 首曲目时,它们相互重叠,我如何在播放 track2 时暂停 track1?使用 javascript