使用 React API 在屏幕上打印问题不起作用
Using react API to print a question on screen not working
我是 React 的新手,我正在尝试制作一个应用程序向用户显示来自此 api 的问题:https://opentdb.com/api.php?amount=1 并且在用户单击按钮后它应该显示一个新问题。我一直收到无效的挂机呼叫,在尝试找到答案后,我似乎无法找出原因。
这是我的代码:
function FetchQuestion(){
const [triviaq, setTriviaq] = React.useState([]);
React.useEffect(() => {
//fetch
fetch('https://opentdb.com/api.php?amount=1')
.then(response => response.json())
.then(data => {
setTriviaq(data.results[0].question);
})
.catch(err => console.error(err))
}, []);
return(
<div>
Question: {triviaq}
<button onClick={FetchQuestion}> Next Question </button>
</div>
)
}
ReactDOM.render(<FetchQuestion/>, document.getElementById("root"))
</script>```
那是因为您试图调用自己的 React 组件,而不是调用您应该在组件内部定义的函数,以便在 onClick
事件期间触发。
此外,这里您使用 useEffect
而不依赖它,以便仅在初始渲染期间调用它。
创建一个单独的函数,以便在初始渲染和 onClick
事件期间调用,如下所示。
export default function FetchQuestion() {
const [triviaq, setTriviaq] = React.useState([]);
const fetchNextQuestion = () => {
//fetch
fetch("https://opentdb.com/api.php?amount=1")
.then((response) => response.json())
.then((data) => {
setTriviaq(data.results[0].question);
})
.catch((err) => console.error(err));
};
React.useEffect(() => {
fetchNextQuestion();
}, []);
return (
<div>
Question: {triviaq}
<button onClick={fetchNextQuestion}> Next Question </button>
</div>
);
}
希望这能解决您的问题。
我是 React 的新手,我正在尝试制作一个应用程序向用户显示来自此 api 的问题:https://opentdb.com/api.php?amount=1 并且在用户单击按钮后它应该显示一个新问题。我一直收到无效的挂机呼叫,在尝试找到答案后,我似乎无法找出原因。 这是我的代码:
function FetchQuestion(){
const [triviaq, setTriviaq] = React.useState([]);
React.useEffect(() => {
//fetch
fetch('https://opentdb.com/api.php?amount=1')
.then(response => response.json())
.then(data => {
setTriviaq(data.results[0].question);
})
.catch(err => console.error(err))
}, []);
return(
<div>
Question: {triviaq}
<button onClick={FetchQuestion}> Next Question </button>
</div>
)
}
ReactDOM.render(<FetchQuestion/>, document.getElementById("root"))
</script>```
那是因为您试图调用自己的 React 组件,而不是调用您应该在组件内部定义的函数,以便在 onClick
事件期间触发。
此外,这里您使用 useEffect
而不依赖它,以便仅在初始渲染期间调用它。
创建一个单独的函数,以便在初始渲染和 onClick
事件期间调用,如下所示。
export default function FetchQuestion() {
const [triviaq, setTriviaq] = React.useState([]);
const fetchNextQuestion = () => {
//fetch
fetch("https://opentdb.com/api.php?amount=1")
.then((response) => response.json())
.then((data) => {
setTriviaq(data.results[0].question);
})
.catch((err) => console.error(err));
};
React.useEffect(() => {
fetchNextQuestion();
}, []);
return (
<div>
Question: {triviaq}
<button onClick={fetchNextQuestion}> Next Question </button>
</div>
);
}
希望这能解决您的问题。