web-dev-qa-db-fra.com

Rediriger vers la page de connexion dans le routeur React 4

Je suis nouveau pour réagir et j'apprends toujours mon chemin. Je crée une application d'une seule page où l'utilisateur est redirigé vers la page de connexion s'il est connecté. React a un composant de redirection et je ne sais pas comment l'utiliser)

Voici mon 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;

Dans le scénario ci-dessus, je veux que l'utilisateur soit redirigé vers la page/login si l'état connecté est faux, sinon il devrait aller sur la page/protégée

4
Anshul Srivastava

vous pouvez faire ce qui suit par 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);
0
Ram Budha