web-dev-qa-db-ja.com

反応ルーター4のログインページにリダイレクトします。

私は反応するのが初めてで、まだ自分の道を学びます。ログインしている場合にユーザーがログインページにリダイレクトされるシングルページアプリを作成しています。ReactにはRedirectコンポーネントがあり、その使用方法がわかりません

以下は私の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;

上記のシナリオでは、loggedInの状態​​がfalseの場合にユーザーを/ loginページにリダイレクトするか、または/ protectedページに移動する必要があります

4

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