React router v4使用声明性重定向而不渲染当前组件 [英] React router v4 use declarative Redirect without rendering the current component

查看:93
本文介绍了React router v4使用声明性重定向而不渲染当前组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用类似的代码,例如,在用户登录后在我的应用中重定向。代码如下所示:

I am using a similar code like this to redirect in my app after users logged in. The code looks like the following:

import React, { Component } from 'react'
import { Redirect } from 'react-router'

export default class LoginForm extends Component {
  constructor () {
    super();
    this.state = {
      fireRedirect: false
    }
  }

  submitForm = (e) => {
    e.preventDefault()
    //if login success
    this.setState({ fireRedirect: true })
  }

  render () {
    const { from } = this.props.location.state || '/'
    const { fireRedirect } = this.state

    return (
      <div>
        <form onSubmit={this.submitForm}>
          <button type="submit">Submit</button>
        </form>
        {fireRedirect && (
          <Redirect to={from || '/home'}/>
        )}
      </div>
    )

  }
}

触发成功登录后工作正常。但有一种情况是,登录用户进入登录页面并应自动重定向到主页页面(或其他任何页面)。

Works fine when a successful login has been triggered. But there is the case, that logged in users enter the login page and should be automatically redirected to the "home" page (or whatever other page).

我该怎么办?使用Redirect组件而不渲染当前组件和没有(据我所知不鼓励)命令推送到历史记录(例如 componentWillMount )?

How can I use the Redirect component without rendering the current component and without (as far as I understand discouraged) imperative pushing to the history (e.g. in componentWillMount)?

推荐答案

解决方案1 ​​

您可以使用 withRouter HOC通过道具访问历史记录。

You could use withRouter HOC to access history via props.

导入withRouter。

Import withRouter.

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

然后用HOC换行。

// Example code
export default withRouter(connect(...))(Component)

现在您可以访问 this.props.history 。与 componentWillMount()一起使用。

Now you can access this.props.history. Use it with componentWillMount().

componentWillMount() {
  const { history } = this.props;

  if (this.props.authenticated) {
    history.push('/private-route');
  }
}






解决方案2 好多了

以下是 reacttraining

哪种方式适合您。

但你只需要创建 LoginRoute 来处理你描述的问题。

But you just need to create LoginRoute to handle problem you described.

const LoginRoute = ({ component: Component, ...rest }) => (
  <Route
    {...rest} render={props => (
    fakeAuth.isAuthenticated ? (
        <Redirect to={{
          pathname: '/private-route',
          state: { from: props.location }
        }} />
      ) : (
        <Component {...props} />
      )
  )} />
);

< Router /> 只需替换

<Route path="/login" component={Login}/>

with

<LoginRoute path="/login" component={Login}/>

现在每次有人都会尝试访问 / login 路由为经过身份验证的用户,他将被重定向到 / private-route 。这是更好的解决方案,因为如果不满足条件,它不会挂载 LoginComponent

Now everytime somebody will try to access /login route as authenticated user, he will be redirected to /private-route. It's even better solution because it doesn't mount your LoginComponent if condition isn't met.

这篇关于React router v4使用声明性重定向而不渲染当前组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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