reactjs - 使用反应 API 在屏幕上打印问题不起作用
问题描述
我是使用 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>```
解决方案
那是因为您试图调用自己的反应组件,而不是调用您应该在组件内部定义以在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>
);
}
希望这能解决您的问题。
推荐阅读
- java - 使用 java api 为 vsphere 获取 VM 映像
- r - 如何在 R 语言中用双引号括起来 JSON
- vuejs3 - 在 vuejs3 的外部 js 文件中导入 vuex4
- mysql - mySQL Sum Production_Needed Group BY Part_ID
- deep-learning - PyTorch:了解 Adam 的实现
- javascript - 无法记录提取结果
- amazon-web-services - API 网关配置返回 403
- discord - Discord 直接消息限制率
- mysql - 如何在 Web 和数据库(Windows 基础)docker 容器之间建立连接,通过 docker-compose 文件运行?
- vba - 如何使用 selenium vba 在页面名称中使用相同类的所有元素