我试图在导航到ReactJS web应用程序中的其他路由或页面之前,显示未保存更改的对话框。我尝试了不同的解决方案,但没有成功。大多数解决方案与旧版本有关。我需要版本6.0.2 (Router)。任何能在这方面帮助我的人都很感激。
发布于 2022-01-23 13:39:31
发布于 2022-01-11 17:46:48
如果usePrompt
或useBlocker
有任何未保存的更改(例如,在未保存的表单元素中),则可以在离开另一条路由之前检测和显示提示符。
但是,在react v6的v6文档中提到了以下内容:
v5 (以及usePrompt和v6 betas中的useBlocker )不包含在当前发布的v6版本中。
我也查看了Github,即使是当前的6.2.1版本也不支持usePrompt
和useBlocker
。
,但您仍然可以降级到v5或6.0.0-字母5。5下面的代码正在使用react路由器v6.0.0-字母5
import React, { useState, useRef, useEffect } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link,
useHistory,
usePrompt,
useBlocker,
Routes
} from "react-router-dom";
// Sometimes you want to prevent the user from
// navigating away from a page. The most common
// use case is when they have entered some data
// into a form but haven't submitted it yet, and
// you don't want them to lose it.
export default function PreventingTransitionsExample() {
return (
<Router>
<ul>
<li>
<Link to="/">Form</Link>
</li>
<li>
<Link to="/one">One</Link>
</li>
<li>
<Link to="/two">Two</Link>
</li>
</ul>
<Routes>
<Route path="/" exact children={<BlockingForm />} />
<Route path="/one" children={<h3>One</h3>} />
<Route path="/two" children={<h3>Two</h3>} />
</Routes>
</Router>
);
}
function BlockingForm() {
let [isBlocking, setIsBlocking] = useState(false);
usePrompt(
"Hello from usePrompt -- Are you sure you want to leave?",
isBlocking
);
// useBlocker(
// () => "Hello from useBlocker -- are you sure you want to leave?",
// isBlocking
// );
return (
<form
onSubmit={event => {
event.preventDefault();
event.target.reset();
setIsBlocking(false);
}}
>
<p>
Blocking? {isBlocking ? "Yes, click a link or the back button" : "Nope"}
</p>
<p>
<input
size="50"
placeholder="type something to block transitions"
onChange={event => {
setIsBlocking(event.target.value.length > 0);
}}
/>
</p>
<p>
<button>Submit to stop blocking</button>
</p>
</form>
);
}
https://stackoverflow.com/questions/70288198
复制相似问题