React Router 4——监听路由动作并以编程方式继续/停止路由 [英] React Router 4 -- listen to route actions and programmatically continue/stop routing
问题描述
这是我的场景:
- 我有一个用户表单,用户可以在其中输入详细信息
- 我想在用户尝试离开当前页面时创建一条确认消息,即嘿,您有未保存的更改"
- 我的组件是我的路由指定的组件,因此它可以访问匹配项、位置、路由和历史记录.
- 我知道是否有历史记录的监听和阻止功能,但我们如何实现这一点?我们可以在某个生命周期中的某个地方调用这些函数,或者你们有其他想法来实现这一点吗?
参考:
Codesandbox 示例(不是我的)
查找教程 这里
在此处查看
文档:文档
this is my scenario:
- I have a user form where user inputs details
- I want to create a confirmation message when user tries to leave current page i.e. "Hey you have unsaved changes"
- My component is a component specified by my route so it has access to match, location, route, and history.
- I am aware if the listen and block function of history but how do we achieve this? can we call these function in a life cycle somewhere or do you guys have any other idea to achieve this?
references:
https://github.com/ReactTraining/history#listening
https://github.com/ReactTraining/history#blocking-transitions
my question:
How to listen to router when user leaves current page/route? (you get the point)
programmatically allow user to continue or not
There is a specific component in react-router just for that specific purpose: <Prompt>
Quoting from the readme:
Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a
<Prompt>
.
The <Prompt>
has when and message props. The prompt is displayed when the user tries to navigate away and when is set to true. So you can have a function set some bool variable to true/false according to your requirement and pass it as a prop to the <Prompt>
For example:
//your component where you get user input
state = {
name: "",
};
render() {
return (
<div>
<div>
<Prompt
when={!!this.state.name} /* triggers the display of prompt */
/*(checks if this.state.name is set)*/
message={location => `You have unsaved changes. Are you sure you want to go to ${location.pathname}?`}
/>
<div>Nice looking profile! What's your name?</div>
<input value={this.state.name} onChange={e => this.setState({ name: e.target.value })} />
</div>
</div>
);
}
Codesandbox sample (not mine)
Find the tutorial here
Check the <Prompt>
documentation here: docs
这篇关于React Router 4——监听路由动作并以编程方式继续/停止路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!