【问题标题】:react-router Redirect vs history.pushreact-router重定向与history.push
【发布时间】:2018-07-15 03:24:06
【问题描述】:

我正在阅读react-router-redux examples,我很困惑, 两者有什么区别:

import { Redirect } from 'react-router-dom'

...

<Redirect to='/login' /> 

import { push } from 'react-router-redux'

...

push('/login')

【问题讨论】:

  • 参见reacttraining.com/react-router/web/api/Redirect :一个简单的重定向会在历史堆栈中添加一个条目(你可以回到之前的路由);如果pushfalse,那么当前url路由被覆盖,不能使用返回键返回到刚刚离开的状态。
  • @Piran,不正确。 Redirect 会覆盖当前历史记录,除非您指定 push 属性(根据您提供的链接)

标签: react-router react-router-v4 react-router-redux react-router-dom


【解决方案1】:

在我使用 Redux 和 Typescript 的用例中,我注意到两者之间存在差异。

这是它的简化版本:

export const LandingPage = () => {
  const { history } = useHistory();
    const { viewer } = useSelector(state => state.viewer);

    // Redirect method returns another component that handles the redirect
    // without mounting any of the route components
    if (!viewer?.token) {
        return <Redirect to="/signin" />;
    }

    // History.push method mounts the route component and runs 'onload' functions
    // Which can still throw an error if there's no viewer 
    // if (!viewer?.token) {
    //  history.push('/signin');
    //    // return history.push('/signin');  // throws Typescript error
    // }

    return (
        <Switch>
            <Route path="/dashboard" component={Dashboard}/>
            <Route path="/profile" component={Profile}/>
            <Route path="/" component={Home}/>
        </Switch>
    );
};

使用 history.push() 方法时,return 语句中的 JSX 仍然可以挂载和运行,而返回 Redirect 会阻塞其余代码。

【讨论】:

    【解决方案2】:

    默认情况下,&lt;Redirect&gt; 组件会将当前位置替换为历史堆栈中的新位置,基本上用作服务器端重定向。

    但它也可以与属性push 一起使用,在这种情况下,它将向历史堆栈推送一个新条目,其工作方式与history.push 相同。

    实际上&lt;Redirect&gt; 组件在幕后使用了历史pushreplace 方法。它只是一种更 React 的导航方式。

    所以基本上你有两种导航方式:

    1. 在组件中使用history.pushhistory.replace(通常用withRouter HOC 包裹,这样您就可以访问location 对象,而无需将其从父级传递给子级。

    2. 使用&lt;Redirect&gt; 组件,有或没有push 属性,具体取决于

    【讨论】:

      【解决方案3】:

      重定向

      渲染&lt;Redirect&gt; 将导航到新位置。新位置将 override the current location in the history stack, 像服务器端重定向 (HTTP 3xx) 一样。

      历史

      推送功能 Pushes a new entry onto the history stack

      【讨论】:

      • 覆盖当前历史堆栈有什么好处?
      • @DollarAkshay,用户在尝试返回时未被阻止。
      猜你喜欢
      • 2018-06-06
      • 2021-02-01
      • 1970-01-01
      • 2020-08-23
      • 2021-10-05
      • 2018-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      相关资源
      最近更新 更多