首页 > 解决方案 > 使用反应 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>```

标签: reactjsreact-hooksfetch-api

解决方案


那是因为您试图调用自己的反应组件,而不是调用您应该在组件内部定义以在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>
  );
}

希望这能解决您的问题。


推荐阅读