React router dom v6 防止在没有 <Prompt> 的情况下进行转换

dev*_*l69 5 javascript reactjs react-router-dom page-transition

我了解到,使用react-router-dom v5,可以使用该<Prompt>组件在页面转换发生之前询问用户,以便用户可以阻止它。

现在,他们暂时从 v6 中删除了它(计划“稍后”有一个强大的实现)。相反,他们建议您自己实现一个等效的组件……我现在就想这样做。

但是:我发现没有办法真正阻止react-router-dom v6中的页面转换。有人知道吗?

Dre*_*ese 5

您可以,但它需要使用自定义history对象和HistoryRouter. 因为这history@5需要是一个包依赖项。

  1. 导入版本 5 的history.

    npm i -S history@5
    
    Run Code Online (Sandbox Code Playgroud)
  2. 创建并导出自定义history对象。

    import { createBrowserHistory } from 'history';
    
    export default createBrowserHistory();
    
    Run Code Online (Sandbox Code Playgroud)
  3. 导入并渲染 aHistoryRouterhistory作为 prop 传递。

    ...
    import { unstable_HistoryRouter as Router } from "react-router-dom";
    import history from './history';
    ...
    
    <Router history={history}>
      <App />
    </Router>
    
    Run Code Online (Sandbox Code Playgroud)
  4. 请遵循阻止转换的文档。

    // Block navigation and register a callback that
    // fires when a navigation attempt is blocked.
    let unblock = history.block((tx) => {
      // Navigation was blocked! Let's show a confirmation dialog
      // so the user can decide if they actually want to navigate
      // away and discard changes they've made in the current page.
      let url = tx.location.pathname;
      if (window.confirm(`Are you sure you want to go to ${url}?`)) {
        // Unblock the navigation.
        unblock();
    
        // Retry the transition.
        tx.retry();
      }
    });
    
    Run Code Online (Sandbox Code Playgroud)

演示:

编辑 agitated-blackwell-dpl9b3