This blog is, based on the react of hook scaffolding, cooperate with the react — the router config the react – the router – dom to build the routing structure, introduction, the structure is clear, convenient management…

Demo has been published on Github ==

Feel ok to point a little star, thank you!

  • Making address: https://github.com/babybrotherzb/React-Router4

If you have written a VUE route, you will know that the vUE route is configured in the New Router. It is easy to write and manage. However, the React route has limitations and is not easy to manage.

import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)
let roles = [
        {
            path: '/',
            component: home,
            redirect: '/home/first',
            children: allroutes()
        },
        {
            path: '/login',
            component: login
        },
        {
            path: The '*',
            redirect: '/'}]const router = new Router({
    routes: roles
})
Copy the code
import React from 'react'
import { Router, Route, Link } from 'react-router'

const App = React.createClass({
  render() {
    return (
      <div>
        <h1>App</h1>
        <ul>
          <li><Link to="/about">About</Link></li>
          <li><Link to="/inbox">Inbox</Link></li>
        </ul>
        {this.props.children}
      </div>
    )
  }
})

const About = React.createClass({
  render() {
    return <h3>About</h3>
  }
})

const Inbox = React.createClass({
  render() {
    return (
      <div>
        <h2>Inbox</h2>
        {this.props.children || "Welcome to your Inbox"}
      </div>
    )
  }
})

const Message = React.createClass({
  render() {
    return <h3>Message {this.props.params.id}</h3>
  }
})

React.render((
  <Router>
    <Route path="/" component={App}>
      <Route path="about" component={About} />
      <Route path="inbox" component={Inbox}>
        <Route path="messages/:id" component={Message} />
      </Route>
    </Route>
  </Router>
), document.body)
Copy the code

Before react Router 4.0, the router == tag could not be nested inside the router == tag. The flexibility of routing was greatly reduced, and the routing hierarchy was not clear, especially when routing was designed to be nested.


React-router-config and react-router-dom can be used to configure routes in a unified manner.

1. Build a React base project

npm install -g create-react-app
create-react-app my-app
cd my-app/
npm start
Copy the code

NPM install react-router-config react-router-dom // check whether package.json is successful


Router folder – AllPhones.js

Routing can be structured and configured in the same way as writing vUE

import AllComponent from '.. /components'
import Home from '.. /components/Home'
import Child from '.. /components/Childs'
import First from '.. /components/Childs/First'
import Second from '.. /components/Childs/Second'
import Other from '.. /components/Other'
import Setting from '.. /components/Set'

const routes = [ {
        path: '/',
        component: AllComponent,// Take special care when a component has child components
        routes: [ {
                path: '/home',
                component: Home,
                routes: [],
            },
            {
                path: '/child',
                component: Child,
                routes: [ {
                        path: '/child/first',
                        component: First,
                        routes: []
                    },
                    {
                        path: '/child/second',
                        component: Second,
                        routes: []
                    }
                ],
            },
            {
                path: '/other',
                component: Other,
                routes: [],
            },
            {
                path: '/set',
                component: Setting,
                routes: [],
            },
        ],
    },
]
export default routes
Copy the code

Router folder -index. JSX

React-router-config is used to save the Route== Route== tag.

import React from 'react' import { renderRoutes } from 'react-router-config' import { BrowserRouter } from 'react-router-dom' import routes from './allroutes' const Router = () => ( <BrowserRouter>{renderRoutes(routes)}</BrowserRouter> </BrowserRouter> Instead of rendering all routes at once, export default RouterCopy the code

RenderRoutes replaces the following traversal process.

 {routes.map((route, i) => (
      <Route
        key={route.key || i}
        path={route.path}
        exact={route.exact}
        strict={route.strict}
        render={(props) => {
          if(! route.requiresAuth || authed || route.path === authPath) {return<route.component {... props} {... extraProps} route={route} /> }return <Redirect to={{ pathname: authPath, state: { from: props.location } }} />
        }}
      />
    ))}
Copy the code

Components folder – Sider folder -index.jsx

So here’s the normal menu, you can render it anywhere you want, right

import React, { memo } from 'react' import { Link } from 'react-router-dom' export default memo(function Sider() { return ( <div ClassName ="route"> <Link to="/home"> home </Link> <Link to="/child"> </Link> <Link to="/other"> other </Link> <Link To ="/set"> set </Link> </div>)})Copy the code

Components folder – index. JSX

import React, { memo ,useEffect} from 'react' import { renderRoutes } from 'react-router-config' import { withRouter} from 'react-router-dom' import Sider from './Sider' export default memo(withRouter(function AllComponent(props) { Console. log(props. Route,'props. Route ',props. UseEffect (() => {if(props.location. Pathname === '/'){props.history.push('/home')}}, [props. Location.pathname]) return (<div> <Sider /> <div className="content"> {renderRoutes(props. Route.routes) } </div> </div>)} </div> </div>)}Copy the code

Components folder -Childs folder – index. JSX

The childs folder is also nested with routes, so renderRoutes() is also used, which means that to render a route child, you need to specify the location of the route child.

import React, { memo ,useEffect } from 'react' import { renderRoutes } from 'react-router-config' import { Link } from 'react-router-dom' import { withRouter} from 'react-router-dom' export default memo(withRouter(function Index(props) { console.log(props.route.routes,'props.route.routes') useEffect(() => { if(props.location.pathname === '/child'){ props.history.push('/child/first') } }, [props.location.pathName]) return (<div> <div className="secondroute"> <Link to="/child/first"> </Link> <Link To ="/child/second"> </Link> </div> <div className="content"> {renderRoutes(props. Route. Routes)} </div> </div>)}))Copy the code

Components folder – Other folder -index. JSX

A simple basic component like this

import React, { memo } from 'react'

export default memo(function Other() {
    return (
        <div className="content">
            other
        </div>
    )
})

Copy the code

The net effect is as follows.

Demo has been published on Github ==

Feel ok to point a little star, thank you!

  • Making address: https://github.com/babybrotherzb/React-Router4