reactjs - 尝试运行定制的钩子,使用了这个 api“https://type.fit/api/quotes”。我能够在对象中获得一堆引号,但无法获得引号
问题描述
我是一个新手,在这里我正在尝试定制钩子。我正在使用这个 API “https://type.fit/api/quotes” 我面临的问题是,没有得到任何错误,也没有在我的输出中得到任何引号。请帮助我找出并理解问题所在
function App() {
const [quote, setQuote]=useState();
useEffect(() => {
const fetchQuote =async()=>{
await fetch("https://type.fit/api/quotes")
.then(
(response)=>response.json())
.then(
(data)=>{setQuote(data.value)});
// console.log(text);
}
fetchQuote();
}, [])
return (
<div>
<h1>Random Quotes</h1>
<p>{quote}</p>
<button>Click For Random Quotes</button>
</div>
);
}
解决方案
响应是一个数组
// 20211109225522 // https://type.fit/api/quotes [ { "text": "Genius is one percent inspiration and ninety-nine percent perspiration.", "author": "Thomas Edison" }, { "text": "You can observe a lot just by watching.", "author": "Yogi Berra" }, { "text": "A house divided against itself cannot stand.", "author": "Abraham Lincoln" }, ...
所以data.value
是未定义的,只需存储data
在状态中并适当地渲染。
function App() {
const [quotes, setQuotes] = useState([]);
useEffect(() => {
const fetchQuote = async () => {
await fetch("https://type.fit/api/quotes")
.then((response) => response.json())
.then((data) => setQuotes(data));
};
fetchQuote();
}, []);
return (
<div>
<h1>Random Quotes</h1>
<ul>
{quotes.map(({ author, text }, index) => (
<li key={index}>
"{text}" ~{author}
</li>
))}
</ul>
<button>Click For Random Quotes</button>
</div>
);
}
推荐阅读
- visual-studio - Visual Studio 可以像 gdb 一样在调试期间使用功能吗?
- authentication - 将包上传到 Nexus 时出现随机“401 Unauthorized”错误
- aframe - 无法通过 A 帧中的耳机移动更新相机的旋转
- excel - VBA替换字符串EXCEL 2019
- javascript - 使用 document.getElementById('element-id').innerHTML 的更快替代方法是什么?
- python - Seaborn 为条形图中的特定条设置颜色
- javascript - 如何使用 JavaScript 检查 cps?
- android - Android,使用 FragmentContainerView 的后退按钮导航关闭应用程序而不是转到上一个片段
- angular - node.name 在 Angular 的 Component.ts 中不起作用
- excel - Excel:从开始日期和结束日期生成月份数据