问题描述
我的 React 应用中有一个页面,如果表单脏了,我想防止用户离开.
There's a certain page in my React app that I would like to prevent the user from leaving if the form is dirty.
在我的反应路线中,我使用的是这样的 onLeave 道具:
In my react-routes, I am using the onLeave prop like this:
<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>
而我的 onLeave
是:
const checkForm = (nextState, replace, cb) => {
if (form.IsDirty) {
console.log('Leaving so soon?');
// I would like to stay on the same page somehow...
}
};
有没有办法防止新路由触发并使用户保持在同一页面上?
Is there a way to prevent the new route from firing and keep the user on the same page?
推荐答案
为时已晚,但根据 React 路由器文档
你可以使用 preventing transition
和 组件的帮助.>
It is too late but according to the React Router Documentation
you can use preventing transition
with helping of <prompt>
component.
<Prompt
when={isBlocking}
message={location =>
`Are you sure you want to go to ${location.pathname}`
}
/>
如果 isBlocking
等于 true
它显示一条消息.有关更多信息,您可以阅读文档.
if isBlocking
equal to true
it shows a message. for more information you can read the documentation.
这篇关于如何使用 react-router 防止路由更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!