简体   繁体   中英

How to load a component on page load in ReactJS?

I have a React JS component am attempting to load into a page after a user has logged in. This secure page consist of tabs and upon clicking the tabs, content is loaded from the tabs respective component. Currently, the main component loads when it's tab is clicked, however I'm attempting to also have that main page load automatically following user login.

This is the Code behind the master page:

import React, { Component } from 'react';
import './App.css';
import AuthService from './components/AuthService';
import withAuth from './components/withAuth';
import Footer from './components/Footer';
import Navigation from './components/Navigation';

import {
  Route,
  NavLink,
  HashRouter
} from "react-router-dom";

import Main from './components/Main';
import Catalog from './components/Catalog ';
import Calendar from './components/Calendar';

const Auth = new AuthService();

class App extends Component {
  render() {
    return (
      <div className="App">
        <div className="App-header">
           <div className="App-title"><h2>Catalog</h2></div>
           <div>
              <p className="App-logout">
                  <button type="button" className="form-submit" onClick={this.handleLogout.bind(this)}>Logout</button>
              </p>
          </div>
        </div>
        <div className="App-divider"></div>
        <div>
            <Navigation />
        </div>
        <div className="App-content">
        <HashRouter>
            <Route exact path="/main" component={Main} />
          </HashRouter>
        <HashRouter>
          <Route path="/catalog" component={Catalog} />
        </HashRouter>
        <HashRouter>
          <Route path="/calendar" component={Calendar} />
        </HashRouter>

        </div>
        <div>
        <Footer />
        </div>
      </div>
    );
  }

  handleLogout() {
    Auth.logout()
    this.props.history.replace('/login');
 }

}

export default withAuth(App);

Am still new to React JS, could I get some help with this? ...Thanks

You probably should separate your unauthenticated views and authenticated views.

Have a login page that stores auth credentials however you'd like, (redux, locally, cookies, etc) then create a route that only shows once the user has auth...

  <Route exact path="/login" component={() => !this.props.auth ? <LoginPage /> : <Redirect to="/HomePage" />} 
  />

// You could also use !this.state.auth, or any other variable you are using to handle auth.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM