使用 React Router 重定向页面的最佳方法是什么?

IT技术 reactjs redux react-router
2021-04-12 01:33:08

我是 React Router 的新手,并了解到有很多方法可以重定向页面:

  1. 使用 browserHistory.push("/path")

    import { browserHistory } from 'react-router';
    //do something...
    browserHistory.push("/path");
    
  2. 使用 this.context.router.push("/path")

    class Foo extends React.Component {
        constructor(props, context) {
            super(props, context);
            //do something...
        }
        redirect() {
            this.context.router.push("/path")
        }
    }
    
    Foo.contextTypes = {
        router: React.PropTypes.object
    }
    
  3. 在 React Router v4 中,有this.context.history.push("/path")this.props.history.push("/path")详细信息:如何在 React Router v4 中推送到历史记录?

我对所有这些选项感到困惑,是否有重定向页面的最佳方法?

5个回答

实际上,这取决于您的用例。

1)您想保护您的路线免受未经授权的用户的侵害

如果是这种情况,您可以使用被调用的组件<Redirect />并可以实现以下逻辑:

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

const ProtectedComponent = () => {
  if (authFails)
    return <Redirect to='/login'  />
  }
  return <div> My Protected Component </div>
}

请记住,如果您想<Redirect />按照您期望的方式工作,您应该将它放在组件的 render 方法中,这样它最终应该被视为一个 DOM 元素,否则它将无法工作。

2)您想在某个操作后重定向(假设在创建项目后)

在这种情况下,您可以使用历史记录:

myFunction() {
  addSomeStuff(data).then(() => {
      this.props.history.push('/path')
    }).catch((error) => {
      console.log(error)
    })

或者

myFunction() {
  addSomeStuff()
  this.props.history.push('/path')
}

为了访问历史记录,您可以使用名为withRouter. 当你用它包装你的组件时,它会传递match locationhistoryprops。有关更多详细信息,请查看withRouter的官方文档

如果你的组件是一个的子<Route />组件,即如果是这样<Route path='/path' component={myComponent} />,你不必换用您的组件withRouter,因为<Route />传球matchlocationhistory它的孩子。

3)点击某个元素后重定向

这里有两个选项。您可以history.push()通过将其传递给onClick事件来使用

<div onClick={this.props.history.push('/path')}> some stuff </div>

或者您可以使用<Link />组件:

 <Link to='/path' > some stuff </Link>

我认为这种情况下的经验法则是首先尝试使用<Link />,我想特别是因为性能。

在最后一个选项中,因为该组件history在其 props 中可以执行this.props.history.push('/path'),这意味着该组件是其子组件<Route/>或它withRouter在导出中具有包装器是否正确?
2021-05-30 01:33:08
它对我有用` this.props.history.push("/");` React-router--v4.2谢谢@Cagri
2021-06-02 01:33:08
所以可以在不指定的情况下路由到另一个组件<Route path='/path' component={Comp}/>,我猜只是render() { return <Comp/>}在某种情况下?
2021-06-11 01:33:08
2021-06-13 01:33:08
@Andre 是的,使用是正确的,this.props.history但是我不确定你的第二个问题是否正确?你到底是什么意思route to another component
2021-06-16 01:33:08

你也可以使用 react router dom 库 useHistory;

import { useHistory } from "react-router-dom";

function HomeButton() {
  let history = useHistory();

  function handleClick() {
    history.push("/home");
  }

  return (
    <button type="button" onClick={handleClick}>
      Go home
    </button>
  );
}

https://reactrouter.com/web/api/Hooks/usehistory

现在有了 react-routerv15.1以后,我们就可以useHistory挂钩了,这是超级简单明了的方法。这是源博客中的一个简单示例。

import { useHistory } from "react-router-dom";

function BackButton({ children }) {
  let history = useHistory()
  return (
    <button type="button" onClick={() => history.goBack()}>
      {children}
    </button>
  )
}

您可以在任何功能组件和自定义挂钩中使用它。是的,这不适用于与任何其他钩子相同的类组件。

在此处了解更多信息https://reacttraining.com/blog/react-router-v5-1/#usehistory

您也可以RedirectRoute如下。这是用于处理无效路由。

<Route path='*' render={() => 
     (
       <Redirect to="/error"/>
     )
}/>

最简单的方法之一:使用Link如下:

import { Link } from 'react-router-dom';

<Link to={`your-path`} activeClassName="current">{your-link-name}</Link>

如果我们想覆盖整个 div 部分作为链接:

 <div>
     <Card as={Link} to={'path-name'}>
         .... 
           card content here
         ....
     </Card>
 </div>