我是 React 的新手,在這里我正在嘗試使用自定義鉤子。我正在使用這個 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>
);
}
uj5u.com熱心網友回復:
回應是一個陣列
// 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>
);
}

轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/358592.html
