使用 React Router 重定向页面的最佳方法是什么? [英] What is the best way to redirect a page using React Router?

查看:23
本文介绍了使用 React Router 重定向页面的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

    import { browserHistory } from 'react-router';//做一点事...browserHistory.push("/path");

  2. 使用this.context.router.push("/path")

    class Foo 扩展了 React.Component {构造函数(道具,上下文){超级(道具,上下文);//做一点事...}重定向(){this.context.router.push("/path")}}Foo.contextTypes = {路由器:React.PropTypes.object}

  3. 在 React Router v4 中,有 this.context.history.push("/path")this.props.history.push("/path").详细信息:如何在 React Router v4 中推送到历史记录?

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

实际上这取决于您的用例.

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

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

从 'react' 导入 React从'react-router-dom'导入{重定向}const ProtectedComponent = () =>{如果(身份验证失败)返回 <重定向到='/登录'/>}返回 

我的受保护组件

}

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

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

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

myFunction() {addSomeStuff(data).then(() => {this.props.history.push('/path')}).catch((错误) => {控制台日志(错误)})

myFunction() {添加一些东西()this.props.history.push('/path')}

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

如果您的组件是 <Route/> 组件的子组件,即如果它类似于 <Route path='/path' component={myComponent}/>,你不必用withRouter 包裹你的组件,因为 通过matchlocationhistory 到它的孩子.

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

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

一些东西

或者你可以使用 组件:

 

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

I am new to React Router and learn that there are so many ways to redirect a page:

  1. Using browserHistory.push("/path")

    import { browserHistory } from 'react-router';
    //do something...
    browserHistory.push("/path");
    

  2. Using 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. In React Router v4, there's this.context.history.push("/path") and this.props.history.push("/path"). Details: How to push to History in React Router v4?

I'm so confused by all these options, is there a best way to redirect a page?

解决方案

Actually it depends on your use case.

1) You want to protect your route from unauthorized users

If that is the case you can use the component called <Redirect /> and can implement the following logic:

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

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

Keep in mind that if you want <Redirect /> to work the way you expect, you should place it inside of your component's render method so that it should eventually be considered as a DOM element, otherwise it won't work.

2) You want to redirect after a certain action (let's say after creating an item)

In that case you can use history:

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

or

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

In order to have access to history, you can wrap your component with an HOC called withRouter. When you wrap your component with it, it passes match location and history props. For more detail please have a look at the official documentation for withRouter.

If your component is a child of a <Route /> component, i.e. if it is something like <Route path='/path' component={myComponent} />, you don't have to wrap your component with withRouter, because <Route /> passes match, location, and history to its child.

3) Redirect after clicking some element

There are two options here. You can use history.push() by passing it to an onClick event:

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

or you can use a <Link /> component:

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

I think the rule of thumb with this case is to try to use <Link /> first, I suppose especially because of performance.

这篇关于使用 React Router 重定向页面的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆