gpt4 book ai didi

reactjs - 如何使用react-router防止路由改变

转载 作者:行者123 更新时间:2023-12-03 13:08:39 25 4
gpt4 key购买 nike

我的 React 应用程序中有一个特定页面,如果表单脏了,我想阻止用户离开该页面。

在我的 react 路由中,我使用 onLeave 属性,如下所示:

<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...
}
};

有没有办法防止新路由触发并使用户保持在同一页面上?

最佳答案

为时已晚,但根据 React Router Documentation 您可以使用preventing transition<prompt> 的帮助下组件。

  <Prompt
when={isBlocking}
message={location =>
`Are you sure you want to go to ${location.pathname}`
}
/>

如果isBlocking等于 true它显示一条消息。有关更多信息,您可以阅读文档。

关于reactjs - 如何使用react-router防止路由改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37145404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com