使用react-router v4重定向到登录页面

时间:2017-06-21 02:58:54

标签: javascript reactjs web-applications react-router react-router-v4

我是React的新手。

我想创建一个默认重定向到登录的amdin应用程序(隐藏主菜单)。使用 react-router v4 ,根据此sample,默认情况下已显示菜单。这样做的最佳做法是什么?这是我目前的代码

index.js

中的

import React from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter,
  Route,
  Switch
} from 'react-router-dom';
import createHistory from 'history/createBrowserHistory'
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import App from './App';
import Login from './modules/Login';

ReactDOM.render((
    <BrowserRouter history={createHistory}>
        <Switch>
            <Route path="/login" component={Login} />
            <Route path="/" component={App} />
        </Switch>
    </BrowserRouter>
    ), document.getElementById('root'));
registerServiceWorker();
app.js

中的

import React from 'react'
import {
  BrowserRouter,
  Link,
  Switch,
  Route,
  Redirect
} from 'react-router-dom'
import { routes } from './router-config'
import Login from './modules/Login'
import fakeAuth from './Auth'

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

const App = () => (
  <BrowserRouter>
    <div>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/protected">Protected</Link></li>
      </ul>

      <Switch>
      {routes.map((route,index) => (
        <PrivateRoute key={index} path={route.pattern} component={route.component} exact={route.exactly} />
      ))}
      </Switch>

    </div>
   </BrowserRouter>
)

export default App
login.js

中的

import React, { Component } from 'react'
import {
  Redirect
} from 'react-router-dom'
import fakeAuth from '../Auth'
import App from '../App'

class Login extends Component {
  state = {
    redirectToReferrer: false
  }

  login = () => {
    fakeAuth.authenticate(() => {
      this.setState({ redirectToReferrer: true })
    })
  }

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

    if (fakeAuth.isAuthenticated) {
      return (
        <Redirect to={"/"}/>
      )
    }

    return (
      <div>
        <p>You must log in to view the page at {from.pathname}</p>
        <button onClick={this.login}>Log in</button>
      </div>
    )
  }
}

export default Login;

我能够点击登录并重定向到应用程序,但是当我在App中刷新页面时,网址会更改为/ login但显示仍在应用程序中。请帮忙。非常感谢

1 个答案:

答案 0 :(得分:5)

我通过创建组件并在App中加载它来解决了这个问题 这是我在 app.js 中的代码:

import React from 'react'
import {
  BrowserRouter,
  Link,
  Switch,
  Route,
  Redirect,
  withRouter
} from 'react-router-dom'
import { routes } from './router-config'
import Login from './modules/Login'
import fakeAuth from './Auth'
import About from './modules/About'
import Protected from './modules/Protected'
import './App.css';

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

const AuthButton = withRouter(({ history }) => (
  fakeAuth.isAuthenticated ? (
    <div>
      Welcome! <button onClick={() => {
        fakeAuth.signout(() => history.push('/login'))
      }}>Sign out</button>
      <ul>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/protected">Protected Page</Link></li>
      </ul>
    </div>
  ) : (
    <Redirect to={{
        pathname: '/login'
      }}/>
  )
))

const App = () => (
  <BrowserRouter>
    <div>
      <AuthButton/>
      <Route path="/login" component={Login}/>
      <PrivateRoute path="/about" component={About}/>
      <PrivateRoute path="/protected" component={Protected}/>
    </div>
  </BrowserRouter>
)

export default App

<强> Login.js

import React, { Component } from 'react'
import {
  Redirect
} from 'react-router-dom'
import fakeAuth from '../Auth'

class Login extends React.Component {
  state = {
    redirectToReferrer: false
  }

  login = () => {
    fakeAuth.authenticate(() => {
      this.setState({ redirectToReferrer: true })
    })
  }

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

    if (redirectToReferrer) {
      return (
        <Redirect to={from}/>
      )
    }

    return (
      <div>
        <p>Please Login</p>
        <div>

        </div>
        <Button onClick={this.login} type="primary">Log in</Button>
      </div>
    )
  }
}

export default Login;

我真的不知道这是否是最好的方法。