我的React应用程序中有一个页面,如果表单脏了,我想阻止用户离开。
在我的反应路线中,我正在使用onLeave道具,如下所示:
<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>
我的onLeave是:
onLeave
const checkForm = (nextState, replace, cb) => { if (form.IsDirty) { console.log('Leaving so soon?'); // I would like to stay on the same page somehow... } };
有没有一种方法可以防止触发新路由并使用户停留在同一页面上?
为时已晚,但是根据React Router Documentation您可以preventing transition在<prompt>组件帮助下使用。
React Router Documentation
preventing transition
<prompt>
<Prompt when={isBlocking} message={location => `Are you sure you want to go to ${location.pathname}` } />
如果isBlocking等于true则显示一条消息。有关更多信息,请阅读文档。
isBlocking
true