简体   繁体   English

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

[英]How to prevent route change using react-router

There's a certain page in my React app that I would like to prevent the user from leaving if the form is dirty.我的 React 应用程序中有一个特定页面,如果表单脏了,我想防止用户离开。

In my react-routes, I am using the onLeave prop like this:在我的反应路线中,我使用的是这样的 onLeave 道具:

<Route path="dependent" component={DependentDetails} onLeave={checkForm}/>

And my onLeave is:我的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?有没有办法防止新路由触发并使用户保持在同一页面上?

It is too late but according to the React Router Documentation you can use preventing transition with helping of <prompt> component.为时已晚,但根据React Router Documentation您可以在<prompt>组件的帮助下使用preventing transition

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

if isBlocking equal to true it shows a message.如果isBlocking等于true则显示一条消息。 for more information you can read the documentation.有关更多信息,您可以阅读文档。

I think the recommended approach has changed since Lazarev's answer, since his linked example is no longer currently in the examples folder.我认为自 Lazarev 的回答以来推荐的方法已经改变,因为他的链接示例当前不再位于examples文件夹中。 Instead, I think you should follow this example by defining:相反,我认为你应该通过定义来遵循这个例子

componentWillMount() {
  this.props.router.setRouteLeaveHook(
    this.props.route,
    this.routerWillLeave
  )
},

And then define routerWillLeave to be a function that returns a string which will appear in a confirmation alert.然后将routerWillLeave定义为一个函数,该函数返回一个将出现在确认警报中的字符串。

UPDATE更新

The previous link is now outdated and unavailable.以前的链接现已过时且不可用。 In newer versions of React Router it appears there is a new component Prompt that can be used to cancel/control navigation.在较新版本的 React Router 中,似乎有一个新组件Prompt可用于取消/控制导航。 See this example这个例子

React-router api provides a Transition object for such cases, you can create a hook in a willTransitionTo lifecycle method of the component, you are using. React-router api 为这种情况提供了一个Transition对象,你可以在你正在使用的组件的willTransitionTo生命周期方法中创建一个钩子。 Something like (code taken from react-router examples on the github):类似于(取自 github 上的 react-router 示例的代码):

var Form = React.createClass({

  mixins: [ Router.Navigation ],

  statics: {
    willTransitionFrom: function (transition, element) {
      if (element.refs.userInput.getDOMNode().value !== '') {
        if (!confirm('You have unsaved information, are you sure you want to leave this page?')) {
          transition.abort();
        }
      }
    }
  },

  handleSubmit: function (event) {
    event.preventDefault();
    this.refs.userInput.getDOMNode().value = '';
    this.transitionTo('/');
  },

  render: function () {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <p>Click the dashboard link with text in the input.</p>
          <input type="text" ref="userInput" defaultValue="ohai" />
          <button type="submit">Go</button>
        </form>
      </div>
    );
  }
});

We're using React Router V5, and our site needed a custom prompt message to show up, and this medium article helped me understand how that was possible我们正在使用 React Router V5,我们的站点需要显示自定义提示消息, 这篇中等文章帮助我理解了这是怎么可能的

TLDR: the <Prompt/> component from react-router-dom can accept a function as the message prop, and if that function returns true you'll continue in the navigation, and if false the navigation will be blocked TLDR:react-router-dom 中的<Prompt/>组件可以接受一个函数作为消息道具,如果该函数返回true您将继续导航,如果为false则导航将被阻止

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM