3
我是React中的新成員。使用react-router v4重定向到登錄頁面
我想創建一個默認重定向到登錄的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;
我可以點擊登錄並重定向到應用程序,但是當我刷新頁面時,在應用程序中,網址更改爲/登錄,但顯示仍在應用程序中。請幫忙。非常感謝
這太可笑了。文檔對於以前的版本來說很體面現在我們必須在互聯網上搜尋那些自己想出來的人的點點滴滴。謝謝。 – Barry