React router v4使用声明性重定向而不渲染当前组件

Jan*_*nkt 3 javascript reactjs react-router-v4

我使用的是类似的代码像这样在我的应用程序将用户重定向登录后的代码如下所示:

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>
    )

  }
}
Run Code Online (Sandbox Code Playgroud)

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

如何在不渲染当前组件的情况下使用Redirect组件(根据我的理解不鼓励)必须推送到历史记录(例如in componentWillMount)?

loe*_*onk 11

解决方案1

您可以使用withRouterHOC通过道具访问历史记录.

导入withRouter.

import {
  withRouter
} from 'react-router-dom';
Run Code Online (Sandbox Code Playgroud)

然后用HOC包裹.

// Example code
export default withRouter(connect(...))(Component)
Run Code Online (Sandbox Code Playgroud)

现在你可以访问了this.props.history.使用它componentDidMount().

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

  if (this.props.authenticated) {
    history.push('/private-route');
  }
}
Run Code Online (Sandbox Code Playgroud)

解决方案2好多了

这是反应训练的例子.

哪个对你有用.

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

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

而内部<Router />只需更换

<Route path="/login" component={Login}/>
Run Code Online (Sandbox Code Playgroud)

<LoginRoute path="/login" component={Login}/>
Run Code Online (Sandbox Code Playgroud)

现在,每当有人试图以经过/login身份验证的用户身份访问路由时,他都会被重定向到/private-route.这是更好的解决方案,因为它没有安装你的LoginComponentif条件不满足.