create react project

npx create-react-app react-router-test

install react-router-dom@5.3.0

npm i react-router-dom@5.3.0

create file /src/RouterHome.jsx, code:

import { Component } from 'react'
export default class RouterHome extends Component {
  render() {
    return (
      <>
        <p><button onClick={()=>this.props.history.push('login')}>Login</button></p>
      </>
    )
  }
}

create file /src/RouterLogin.jsx, code:

import { Component } from 'react'
export default class RouterLogin extends Component {
  render() {
    return (
      <div>RouterLogin</div>
    )
  }
}

create file /src/RouterNotFound.jsx, code:

import { Component } from 'react'
export default class RouterNotFound extends Component {
  render() {
    return (
      <div>RouterNotFound</div>
    )
  }
}

create file /src/routers/index.js, code:

import { BrowserRouter as Router, Switch, Route, useHistory } from "react-router-dom";
// use react-router-dom@5.3.0
import Home from '../RouterHome'
import Login from '../RouterLogin'
import NotFound from "../RouterNotFound";
const BaseRoute = () => {
  return (
    <Router history={useHistory}>
      <Switch>
        <Route exact path="/" component={Home}></Route>
        <Route exact path="/login" component={Login}></Route>
        <Route component={NotFound}></Route>
      </Switch>
    </Router>
  )
}
export default BaseRoute

edit /src/index.js, code:

import ReactDOM from 'react-dom';
import App from './routers/index';
ReactDOM.render(
  <App />,
  document.getElementById('root')
)

run

npm run start

behaviour

access http://localhost:3000/ and http://localhost:3000/bridge and you will see different text
access url not exits, for example http://localhost:3000/abc, you will see text RouterNotFound

添加新评论