Reactjs 加载页面时useEffect()出现问题

Reactjs 加载页面时useEffect()出现问题,reactjs,react-hooks,Reactjs,React Hooks,我的react测验应用程序有问题。以下是描述: 这来自App.js文件: ... const [createQuiz, setCreateQuiz] = useState(false); ... useEffect(()=> { const reRender = () => { setCreateQuiz(true) } window.onload=function(){ document.getElementById("myBtn

我的react测验应用程序有问题。以下是描述: 这来自App.js文件:

...
const [createQuiz, setCreateQuiz] = useState(false);
...
useEffect(()=> {
    const reRender = () => {
        setCreateQuiz(true)
    }
    window.onload=function(){
      document.getElementById("myBtn").addEventListener("click", reRender);
    } 
    // return document.getElementById("myBtn").removeEventListener("click", reRender);
  }, [createQuiz])

return (
    <QuizContextProvider>
      {
      (createQuiz) ? (
        <div>Form</div>
      ) : (
        <div>
        <Modal/>
        <Question question={questions[questionNumber]} next={goToTheNext} />
        </div>
      )
      }
      {console.log(createQuiz)}
    </QuizContextProvider>
  );
}

它没有按预期工作。我在对红男爵的第二次评论中描述了它的起因,请看一看。

实现您想要的功能的正确方法是在
应用程序
组件内创建一个事件处理程序,当在
模式
组件内单击
创建您自己的
按钮时,该组件将
CreateQuit
设置为


function App() {
  const [createQuiz, setCreateQuiz] = React.useState(false);

  const handleShowQuizForm = () => {
    setCreateQuiz(true);
  };

  return (
    <div>
      {createQuiz ? (
        <div>Form</div>
      ) : (
        <>
          <Modal showQuizForm={handleShowQuizForm} />
        </>
      )}
    </div>
  );
}

function Modal(props) {
  return (
    <div>
      <button type="button" onClick={props.showQuizForm}>
        Create your own
      </button>
    </div>
  );
}

只需添加更多状态,指示用户是否单击了现有或创建了自己的html,然后根据这些状态呈现不同的html?我想这是因为
window.onload
。我尝试不使用它,但没有出现错误,即“无法读取null的属性'addEventListener'。这就是为什么我要使用
window.onload
。您不应该使用类似的东西:
window.onload=function(){
您可以在
useffect
中调用函数,它将被调用onload@RedBaron谢谢!它几乎解决了问题!但是在退出开发服务器并重新启动之后,
表单出现了,而不是
。这是我感觉使用
窗口的另一个原因。onload
  const reRender = () => {
    setCreateQuiz(true)
  }

  useEffect(()=> {
    reRender()
    //return setCreateQuiz(false)

  }, [createQuiz])

function App() {
  const [createQuiz, setCreateQuiz] = React.useState(false);

  const handleShowQuizForm = () => {
    setCreateQuiz(true);
  };

  return (
    <div>
      {createQuiz ? (
        <div>Form</div>
      ) : (
        <>
          <Modal showQuizForm={handleShowQuizForm} />
        </>
      )}
    </div>
  );
}

function Modal(props) {
  return (
    <div>
      <button type="button" onClick={props.showQuizForm}>
        Create your own
      </button>
    </div>
  );
}