1 回答
TA贡献1831条经验 获得超9个赞
您错误地使用了地图功能。您应该将函数传递给映射。
const { useState } = React;
const JokeFinder = () => {
const [query, setQuery] = useState("");
const [jokes, setJokes] = useState([]);
const getJokes = 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";
}
fetch(URL).then((result) => {
result.json().then(data => 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>
<div className="input-container">
<input
className="input"
type="text"
name="query"
placeholder="Enter number of Jokes Desired (only one or ten)"
value={query}
onChange={changeHandler}
/>
<button className="button" type="submit">
Search!
</button>
</div>
</form>
<div className="card-list">
{jokes.length ? (
jokes.map((joke, index) => (
<div key={index}>
<p className="setup" >{joke.setup}</p>
<p className="punchline">{joke.punchline}</p>
</div>
))
) : (
<div>
<p className="setup">{jokes.setup}</p>
<p className="punchline">{jokes.punchline}</p>
</div>
)}
</div>
</div>
);
};
class App extends React.Component {
render() {
return (
<JokeFinder />
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
.input-container {
margin-top: 10px;
}
.input-container input {
margin-right: 10px;
min-width: 240px;
}
.setup {
font-weight: 700;
}
.punchline {
padding-left: 10px;
}
<html>
<body>
<div id="root"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
</body>
</html>
你可以在这里找到工作示例
添加回答
举报