如何在react-router-dom v6中显示确认对话框,以确认是否要丢弃输入的信息
想要实现的目标

问题
在React Router v6中,为了防止页面离开,useBlocker函数被删除了,需要另外进行实现。
参考 https://qiita.com/yukiji/items/89d5174f13cdc21a622f#リンクでの遷移戻る進む
使用過的函式庫
react-router-prompt 是一个位于 GitHub 上的项目,地址是 https://github.com/sshyam-gupta/react-router-prompt/tree/main。
实际上,我只复制并使用了这个库中的三个必要文件。
https://github.com/sshyam-gupta/react-router-prompt/blob/main/src/hooks/use-confirm.ts
https://github.com/sshyam-gupta/react-router-prompt/blob/main/src/hooks/use-prompt.ts
https://github.com/sshyam-gupta/react-router-prompt/blob/main/src/index.tsx
因为不确定react-router这个非官方库是否会持续更新,并且由于上述三个文件只需要简单移植就可以使用,所以我选择了将代码移植并使用,而不是直接使用这个库。
这是我自己创建的代码库。
https://github.com/nobu0605/react-router-prompt
当然,你也可以直接使用这个库。
使用方法
不管是使用库还是自己编写,都可以通过调用ReactRouterPrompt,将对话框等包装起来使用。在when属性中传递变更检测标志。
import ReactRouterPrompt from "./ReactRouterPrompt";
import Button from "@mui/material/Button";
import Dialog from "@mui/material/Dialog";
import DialogActions from "@mui/material/DialogActions";
import DialogContent from "@mui/material/DialogContent";
import DialogContentText from "@mui/material/DialogContentText";
import DialogTitle from "@mui/material/DialogTitle";
type Props = {
when: boolean;
};
export function UnsavedConfirmDialog({ when }: Props) {
return (
<ReactRouterPrompt when={when}>
{({ isActive, onConfirm, onCancel }) =>
isActive && (
<Dialog open={isActive}>
<DialogTitle>Do you really want to leave?</DialogTitle>
<DialogContent>
<DialogContentText>
Your changes will not be saved.
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={onCancel}>cancell</Button>
<Button onClick={onConfirm} autoFocus>
ok
</Button>
</DialogActions>
</Dialog>
)
}
</ReactRouterPrompt>
);
}
增添
当试图重新加载页面时,如果要显示确认对话框,可以使用beforeunload事件,但似乎无法显示自定义消息或自制的对话框。
将显示各个浏览器的默认对话框。
https://qiita.com/nantekkotai/items/9a6e2c98ed704934ab47