首页 > 解决方案 > 使用 history.block 后 history.push 不起作用

问题描述

当用户尝试离开当前页面时,我试图显示一条消息,所以我使用 history.block 像这样:

    import { useHistory } from "react-router-dom";
    
    
    const ProfilerCreate = ({ pageType }) => {
    const history = useHistory();
    const [isDisabled, setIsDisabled] = useState(true);
    const [openModalUnsave, setOpenModalUnsave] = useState(false);
    
    useEffect(() => {
        history.block(validateChange);
     }, []
    );
    
    //Function to validate changes and open modal
      function validateChange(txt) {
        if (!isDisabled) {
          toggleModalUnsave();
          return false;
        }
      }

//Function to open or close modal
  function toggleModalUnsave() {
    setOpenModalUnsave(!openModalUnsave);
  }

//Function to return landing page
  function returnPage() {
    history.push("/");
  }
    
    return (
...
<div style={{ display: "none" }}>
        <Modal
          id="myModal"
          heading="You have unsaved changes"
          description="Do you want to save or discard them?"
          isOpen={openModalUnsave}
          onRequestClose={(detail) => toggleModalUnsave()}
          actionsRight={
            <>
              <Button display="text" onClick={() => returnPage()}>
                Discard
              </Button>
              <Button
                display="primary"
                onClick={(evt) => saveAudienceData(evt)}
              >
                Save and exit
              </Button>
            </>
          }
        >
          <p>Modal Children</p>
        </Modal>
      </div>
);
    
    export default ProfilerCreate;

当它检测到未保存的更改时,它会显示一个带有警告和两个按钮的模式,一个用于保存,另一个用于丢弃,当用户点击丢弃按钮时,它应该返回主页,但history.push不工作。

我试图找到解决方案,或者我不知道我是否history.block以错误的方式使用它。

我希望你能帮助我,谢谢!

标签: javascriptreactjsreact-router-dom

解决方案


我认为您缺少中的unblock()方法validateChange(txt)


推荐阅读