[英]Redirect to login page in react router 4
I am new to react and still learning my way around.我是新来的反应和仍在学习我的方式。 I am creating a single page app where the user is redirected to the login page if he is not logged in. React has a Redirect component and I am not sure how to use it.
我正在创建一个单页应用程序,如果他没有登录,用户将被重定向到登录页面。 React 有一个重定向组件,我不知道如何使用它。
Following is my app.js :-以下是我的 app.js :-
import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';
import Login from './components/login/login.js'
import Protected from './components/protected/protected.js'
import './App.css';
class App extends Component {
state = {
loggedIn: false // user is not logged in
};
render() {
return (
<Switch>
<Route path="/protected" component={Protected}/>
<Route path="/login" component={Login}/>
</Switch>
);
}
}
export default App;
In the above scenario, I want the user to be redirected to the /login
page if the state loggedIn
is false or else it should go to the /protected
page.在上述情况下,我希望用户被重定向到
/login
页面,如果状态loggedIn
是假的,否则它应该去/protected
页面。
I usually create a PrivateRoute
component that checks if the user is logged in (via prop, redux, localstorage or something).我通常会创建一个
PrivateRoute
组件来检查用户是否已登录(通过 prop、redux、localstorage 或其他方式)。
Something like:就像是:
const PrivateRoute = ({ isLoggedIn, ...props }) =>
isLoggedIn
? <Route { ...props } />
: <Redirect to="/login" />
In the router I then use it for my, well, private routes :)在路由器中,我将它用于我的私人路线:)
<Switch>
<PrivateRoute isLoggedIn={ this.state.loggedIn } path="/protected" component={Protected} />
<Route path="/login" component={Login}/>
</Switch>
you can do the following by redux-saga,您可以通过 redux-saga 执行以下操作,
import jwt_decode from 'jwt-decode';
//define you saga in store file here
import {store, history} from './store';
// Check for token
if (localStorage.jwtToken) {
// Set auth token header auth
setAuthToken(localStorage.jwtToken);
// Decode token and get user info and exp
const decoded = jwt_decode(localStorage.jwtToken);
// Set user and isAuthenticated
store.dispatch(setCurrentUser(decoded));
// Check for expired token
const currentTime = Date.now() / 1000;
if (decoded.exp < currentTime) {
// Logout user
store.dispatch(logoutUser());
// Clear current Profile
store.dispatch(clearCurrentProfile());
// Redirect to login
window.location.href = '/login';
}
}
const setAuthToken = token => {
if (token) {
// Apply to every request
axios.defaults.headers.common['Authorization'] = token;
} else {
// Delete auth header
delete axios.defaults.headers.common['Authorization'];
}
};
// Set logged in user
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
};
};
// Clear profile
const clearCurrentProfile = () => {
return {
type: CLEAR_CURRENT_PROFILE
};
};
// Log user out
const logoutUser = () => dispatch => {
// Remove token from localStorage
localStorage.removeItem('jwtToken');
// Remove auth header for future requests
setAuthToken(false);
// Set current user to {} which will set isAuthenticated to false
dispatch(setCurrentUser({}));
};
// render part
render() {
return (
<Provider store={store}>
<ConnectedRouter history={history}>
{/* Switch stops searching for the path once the match is found */}
<Switch>
{/* <div> */}
<Route exact path="/" component={Landing} />
<Route exact path="/signup" component={Signup} />
<Route exact path="/login" component={Login} />
<Route exact path="/forgotpassword" component={ForgotPassword} />
<Route exact path="/not-found" component={NotFound} />
<Route exact path="/resetpassword" component={ResetPassword} />
{/* Do not pass 'exact' props. It won't match /dashboard/other_url */}
<Route path="/dashboard" component={DefaultLayout} />
{/* </div> */}
</Switch>
</ConnectedRouter>
</Provider>
);
}
// .store file if you need
import { createBrowserHistory } from 'history'
import {createStore, applyMiddleware } from 'redux';
import { routerMiddleware } from 'connected-react-router'
import { composeWithDevTools } from 'redux-devtools-extension/logOnlyInProduction';
import createSagaMiddleware from 'redux-saga'
import rootReducer from './reducers'
import rootSaga from './sagas/';
export const history = createBrowserHistory();
const sagaMiddleware = createSagaMiddleware()
const myRouterMiddleware = routerMiddleware(history);
const initialState = {};
const middleWare = [myRouterMiddleware,sagaMiddleware];
export const store = createStore(rootReducer(history),
initialState,
composeWithDevTools(applyMiddleware(...middleWare))
);
sagaMiddleware.run(rootSaga);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.