由于某种原因,添加该行{jokes.map(joke => joke.setup)}(请参阅下面的完整组件)会引发错误(如下所示)。我觉得这与 useState 挂钩有关,但我不确定解决方法。任何帮助,将不胜感激!
组件代码如下:
import React, {useState, useEffect} from 'react'
function JokeFinder() {
//2 states: input query, jokes shown
const [query, setQuery] = useState('')
const [jokes, setJokes] = useState([])
const getJokes = async (event) => {
event.preventDefault();
let URL;
try{
if(query === "one" || query === "1") {
URL = `https://official-joke-api.appspot.com/jokes/random`
} else if (query === "ten" || query === "10") {
URL = 'https://official-joke-api.appspot.com/jokes/ten'
}
const result = await fetch(URL);
const data = await result.json();
setJokes(data);
} catch(err) {
console.log(err);
}
}
const changeHandler = (event) => {
setQuery(event.target.value)
}
return(
<div>
<form className="form" onSubmit={getJokes}>
<label className="label" htmlFor="query">It's never a bad time to have a laugh! How many jokes would you like to enjoy? One or ten? Type in the number below.</label>
<input
className="input"
type="text"
name="query"
placeholder="Enter number of Jokes Desired"
value={query}
onChange={changeHandler}
/>
<button className="button" type="submit">Search!</button>
</form>
<div className="card-list">
{jokes.map(joke => joke.setup)}
</div>
</div>
)
}
export default JokeFinder
天涯尽头无女友
相关分类