简体   繁体   English

尝试清除/清空/删除/设置回初始 state 时,React setState 挂钩不起作用

[英]React setState hook is not working when trying to clear/empty/delete/set back to initial state

I have a clearState function which sets some useState hooks back to their initial state when the restart button is clicked.我有一个clearState function 当单击重新启动按钮时,它将一些 useState 挂钩设置回其初始 state。 However, they say that my setState is not a function.但是,他们说我的 setState 不是 function。 Please check code below:请检查以下代码:

App.js应用程序.js

...
const [question, setQuestion] = useState(0);
const [response, setResponse] = useState({});
const [answer, setAnswer] = useState({});
const [answerId, setAnswerId] = useState({});
...

Modal.js模态.js

const Modal = ({
  setResponse,
  setAnswer,
  setAnswerId,
  setQuestion,
  setAnswerNameArr,
}) => {
  const [open, setOpen] = useState(false);

  const clearState = () => {
    setOpen(false); //works
    setQuestion(0); //works
    setAnswer({}); //does not work
    setAnswerId({});
    setResponse({});
    setAnswerNameArr([]);
  };

...

  return (
    <Modal
       ...
    >
      ...
        <Button
           onClick={()=>handleSubmit()}
        >
           Restart
        </Button>
    </Modal>
  );
};

export default Modal;

The error:错误:

Uncaught TypeError: setAnswer is not a function

Thanks in advance.提前致谢。

It looks like you aren't passing your state setting hooks in to your <Modal> so they're not available.看起来您没有将 state 设置挂钩传递到您的<Modal>中,因此它们不可用。

It isn't a good idea to do that anyway, tbh.无论如何,这样做不是一个好主意,tbh。 If you need a child to affect the state of a parent it would be better to pass a single call-back:如果您需要一个孩子来影响父母的 state 最好传递一个回调:

const Modal = ({
      onSubmitCb
}) => {
  const [open, setOpen] = useState(false);

  const clearState = () => {
    setOpen(false); //works
    setQuestion(0); //works
    onSubmitCb && onSubmitCb()
  };

...

  return (
    <Modal>
      ...
        <Button
           onClick={()=>handleSubmit()}
        >
           Restart
        </Button>
    </Modal>
  );
};

and in your parent:在你的父母中:

const App = ()=>{
    const clearState = () => {
        setAnswer({});
        setAnswerId({});
        setResponse({});
        setAnswerNameArr([]);
  };
  
  .... 

  return {
      <Modal ... onSubmitCb={clearState} />
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM