javascript - 使用 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
以错误的方式使用它。
我希望你能帮助我,谢谢!
解决方案
我认为您缺少中的unblock()
方法validateChange(txt)
推荐阅读
- go - Kubernetes Operator Wide Objects 和 Instance Wide Objects
- sparql - 在 SPARQL 中过滤!= NULL
- javascript - 我希望循环只运行一次 - JavaScript
- kinetica - Kinetica 的正确更新语法是什么?
- c# - 如何使用 Dictionary C# 在 JSON 文件中包含描述
- spring - Spring Boot 不阻止对端点的请求
- node.js - Node.js 中转换流的透明度
- c# - 另一种形式的计时器没有停止
- r - 从 ggplot 中删除构面并显示在单个图表上?
- python - 在 docker 容器中运行 .env 文件