为什么我的"new Question"按钮在我单击按钮时没有更改问题?



因此,当您单击按钮时,您应该会看到新的问题。但它不起作用,我不知道为什么:(救命!

const Trivia = () => {
const [question, setQuestion] = React.useState();


React.useEffect(() => {
fetch('https://opentdb.com/api.php?amount=1') 
.then(response => response.json())
.then(data => {
setQuestion(data.results[0].question);
});
}, [] )

return(
<div>
<p>{question}</p> 

<button onClick={() => }> New Question</button>
</div>

);
};

ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>

因此,如果您想在单击按钮时从API中重新提取一个新问题,我建议您将API调用导出为这样的函数:

const fetchQuestion = () => {
fetch("https://opentdb.com/api.php?amount=1")
.then((response) => response.json())
.then((data) => {
setQuestion(data.results[0].question);
});
};

然后你可以随时调用它,你的代码应该是这样的:

const Trivia = () => {
const [question, setQuestion] = React.useState();
const fetchQuestion = () => {
fetch("https://opentdb.com/api.php?amount=1")
.then((response) => response.json())
.then((data) => {
setQuestion(data.results[0].question);
});
};
React.useEffect(() => {
fetchQuestion();
}, []);
return (
<div>
<p>{question}</p>
<button onClick={fetchQuestion}>New Question</button>
</div>
);
};
ReactDOM.render(<Trivia />, document.getElementById("root"));
</script>

最新更新