小编典典

如何使用React-Router防止路由更改

reactjs

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

有没有一种方法可以防止触发新路由并使用户停留在同一页面上?


阅读 348

收藏
2020-07-22

共1个答案

小编典典

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

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

如果isBlocking等于true则显示一条消息。有关更多信息,请阅读文档。

2020-07-22