One, foreword

Recently, I started to learn React. As a reincarnated Vue React, the first thing is that I am dedicated to routing. Vue is so centered in routing and is so easy to use with parent and child routing that I can’t accept the route writing in the React tutorial. So I want to implement centralized routing in React as well.

You can view your favorite writing method through the right side of the directory, does not affect the reading.

The comments section can be used for discussion and any errors are welcome.

In actual development, landing a function is certainly useful or profound, such as the left click like function.

2. Talk about the basic idea of React

You can see the tutorial here

IndexRoute is no longer supported in React-Router4 +

React is not a common component in the current file. It is recommended to generate a component class from React’s React. CreateClass method (which is obsolete), or write a method directly.

/ / component class
const Message = React.createClass({
  render() {
    return <h3>Message {this.props.params.id}</h3>}})Return dom ()
const Index = function(){
    return (
        <React.fragment>// React placeholder tags are not actually rendered<p></this is Index>
            <Link to="/about">About</Link>
        </React.fragment>)}Copy the code

The reason for the above paragraph is that I wrote too much HTML in the root node of the current file just like writing Vue when I first used it, resulting in bloated code. I hope to see the new React of this article, please pay attention to this point.

Back to the topic, React4 has revolutionized routing, making way for a more “componentized” approach in React, changing from “centralized routing” (or “static” routing) in React3 and before to “decentralized routing” (” dynamic routing “).

I want to use “centralized routing” in the React version because it is easy to manage and clear routing. (In fact, it is a little mental axis)

Three, the central route (static route) writing method

In fact, at the beginning, I didn’t read the tutorial carefully and didn’t have a thorough understanding of the “componentization” idea of React. I thought that “componentization” was the developer’s business, while the framework was still in Vue, so I chose the writing method of “centralized route”. And it’s very simple to write, as follows.

// src/route.js
import Home from './pages/index/index';
import HomeNews from './pages/index/component/HomeNews';
import My from './pages/my/my';

const routes = [
  {
    path: "/my".component: My
  },{ // The route is written from the route of the news page. By default, the components displayed on the home page are below. You need to determine in the home page file.
    path: "/".component: Home,
    children: [{path: "/news".component: HomeNews
      }
    ]
  }
]

export {
  routes
}

// src/index.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import reportWebVitals from './reportWebVitals';

import {routes} from './route';
import {BrowserRouter} from 'react-router-dom';
import {renderRoutes} from 'react-router-config';

ReactDOM.render(
  (
    <BrowserRouter>
      {renderRoutes(routes)}
    </BrowserRouter>
  ),
  document.getElementById('root'));// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Copy the code

After reading the above code, some friends may wonder why I put the default route (“/”) at the bottom. Is it because I developed the personal center first?

No, because the React route matches.

In React, routes are obfuscated by default, so if I write this, it will cause the personal center route to preferentially match the home page route.

If I add exact to the home page route, it will cause the expected parent and child components to be invalid

So the home page route is written at the bottom is helpless.

If you want to use “centralized routing” in React, you need to consider the trade-off, because there is a small detail that also needs to be paid attention to.

In a project, the home page of the Web is usually left unchanged at the top, and the content area below is dynamically switched with the navigation bar.

For example, gold, the red box area will not change, the green box part with the navigation bar (home page route) switch and dynamic loading.

The green box of gold mining is different, but in work, the green box (Main) of many projects is also very different layout, including the backend management platform is the same.

So I added a routing judgment to the home page to confirm the components that render that part.

// src/pages/index/index.jsx
class index extends Component {
  constructor(props){
    super(props)
    this.state = {
      route: props.route
    }
  }

  // Determine the user's access address and confirm to load the component
  getPath(){ 
    let route = this.props.location.pathname
    return route === '/'
  }

  render() {
    const route = this.state.route;
    return (
      <div className={` ${s['main']} `} >
        <HeaderTop />
        <div className="container">} {this.getPath()?}} {this.getPath()?<HomeMain /> : renderRoutes(route.children)}
        </div>
        <Footer />
      </div>); }}Copy the code

So far, that’s basically the whole idea and details of my “centralized routing”.

Fourth, decentralized routing (dynamic routing) core ideas

React-router-dom5.2.0: Router4 + : Router4 + : Router4 + : Router4 + : Router4 +

// / SRC /Party/ Party directory is the second section of my project
import React,{Component} from 'react';
import {BrowserRouter as Router, Route, Link} from 'react-router-dom';

import Home from '... ';
import News from '... ';

class party extends Component {
  constructor(props){
    super(props)
  }
  render() {
    return (
      <div>
        <Router>// The navigation must be placed within the Router. Otherwise, the Router will switch routes and the component will not be updated<Nav />// If a child component temporarily wants to hide its header, it can do so by calling the parent component method<Route exact path="/" component={Home} />// Keep the header and the default home page content displayed<Route path="/new" component={News} />
        </Router>
      </div>); }}const Nav = props= > {
  return (
    <nav className={s['nav']} >
      <div className="flex align-items">
        <Link to="/party" className={s['active']} >Home page</Link>
        <Link to="/party">The child pages</Link>
      </div>
    </nav>)}export default party;
Copy the code

Five, the summary

The deletion line deletes the content before modification. After careful thinking, I still choose the decentralized routing writing method of React. The first section has been written, so I will not change it.

If you are new to the project, applying the core code to the home page is normal and not affected.

Take things as they come, and do things after you understand them. I was still honest when I was a beginner. Come on, stranger.