This is the 17th day of my participation in Gwen Challenge

React Route

React builds single-page applications that use routes to redirect pages. React-router and react-router-dom (router V4) are two common packages that implement these requirements.

React-router implements core routing functions

React-router-dom: react-router-dom: react-router-dom: react-router-dom: React-router-dom: React-router-dom: React-router-dom: React-router-dom: React-router-dom: React-router-dom: React-router-dom: React-router BrowserRouter(History)(without #) and HashRouter(with #), the former uses pushState and popState events to build routes, and the latter uses window.localtion.hash and hashchange events to build routes.

2. Handwritten routing

2.1 PREPARING the H5 Environment

Wampserver is a PHP integration tool used to install Apache.

2.2 Opening Localhost in Google Chrome indicates that the environment is installed

2.3 Specifying another Service path

Modify this file

2.4 Restart the server

2.5 Configuration Succeeded

Each of your directories will be a website

2.6 Create an HTML file to simulate a route

<! DOCTYPE html><html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Routing principle</title>
</head>
<body>
<button type="button" onclick="history.go(-1)">return</button><br/>Push model<ul>
        <li onclick="Router.push(baseUrl)">Home page</li>
        <li onclick="Router.push(baseUrl+'news')">news</li>
        <li onclick="Router.push(baseUrl+'product')">product</li>
    </ul>Replace mode<ul>
    <li onclick="Router.replace(baseUrl)">Home page</li>
    <li onclick="Router.replace(baseUrl+'news')">news</li>
    <li onclick="Router.replace(baseUrl+'product')">product</li>
</ul>
<div id="app"></div>
<script>
    var app=document.getElementById("app"),baseUrl="/router/";
    function RouterClass(opts){
        this.routes={};
        this.curUrl="";
        this.mode="";
        if(opts){
            this.mode=opts.mode;
            if(this.mode==='history') {this.eventHistoryRouter();
            }else{
                this.eventHashRouter(); }}else {
            this.eventHashRouter();
        }
    }
    RouterClass.prototype.route=function(path,callback){
        this.routes[path]=callback || function(){}};/ / hash pattern
    RouterClass.prototype.hashRouter=function(){
          this.curUrl=window.location.hash.slice(1) | |'/';
            this.routes[this.curUrl]();
    };
    // Listen for hash routes
    RouterClass.prototype.eventHashRouter=function(){
        window.addEventListener("load".this.hashRouter.bind(this));
        window.addEventListener("hashchange".this.hashRouter.bind(this));
    };
    / / the history model
    RouterClass.prototype.historyRouter=function(){
        this.curUrl=window.location.pathname;
        this.routes[this.curUrl]();
    };
    // Listen for routes in history mode
    RouterClass.prototype.eventHistoryRouter=function(){
        window.addEventListener("load".this.historyRouter.bind(this));
        window.addEventListener("popstate".this.historyRouter.bind(this));
    };

    // Push mode jumps to the page
    RouterClass.prototype.push=function(url){
        if(this.mode==='history') {window.history.pushState({},null,url);
            this.routes[url]();
        }else {
            url="#"+url;
            window.location.href = url; }};// Replace mode redirects the page
    RouterClass.prototype.replace=function(url){
        if(this.mode==='history') {window.history.replaceState({},null,url);
            this.routes[url]();
        }else {
            url = "#" + url;
            window.location.replace(url); }};var Router=new RouterClass({
        mode:"history" //hash: hash,history: no hash
    });
    Router.route(baseUrl,function(){
        app.innerHTML="Home page"
    })
    Router.route(baseUrl+'news'.function(){
        app.innerHTML="News page"
    })
    Router.route(baseUrl+'product'.function(){
        app.innerHTML="Product Page"
    })
</script>
</body>
</html>
Copy the code

React router

3.1 install the react – the router – the dom

npm i --save-dev react-router-dom
Copy the code

3.2

import React from 'react';
import {HashRouter,Route} from 'react-router-dom'
import IndexPage from  './pages/index'

class Router extends React.Component{
    constructor(){
        super(a);this.state={

        };
    }


    componentDidMount(){}render(){
        return (
            <React.Fragment>
                <HashRouter>
                    <React.Fragment>
                        <Route path={'/'} component={IndexPage}></Route>
                    </React.Fragment>
                </HashRouter>
            </React.Fragment>)}}export default Router;

Copy the code

Hash routing

The history of routing

 <BrowserRouter>
    <React.Fragment>
        <Route path={'/'} component={IndexPage}></Route>
    </React.Fragment>
</BrowserRouter>
Copy the code

3.2 Link to can jump to the page

Home page

import  React from 'react'
import {Link} from 'react-router-dom'

class Index extends  React.Component {
    render() {
        return (
            <React.Fragment>
                <div>Home page</div>
                <Link to={'/news'} >
                    <button>Go to the news page</button>
                </Link>
            </React.Fragment>)}}export default Index
Copy the code

The news page

import  React from 'react'
import {Link} from 'react-router-dom'


class Index extends  React.Component {
    render() {
        return (
            <React.Fragment>
                <div>news</div>
                <Link to={'/'} >
                    <button>Back to the home page</button>
                </Link>
            </React.Fragment>)}}export default Index
Copy the code

The effect

3.3 restful style With parameters

The router. In js

  <Route path={'/news/detail/:id/:title'} exact component={NewsDetailPage}></Route>
Copy the code

List of pp.

import  React from 'react'
import {Link} from 'react-router-dom'


class Index extends  React.Component {
    render() {
        return (
            <React.Fragment>
                <div>news</div>
                <ul>
                    <li><Link to={'/news/detail/110/ volcano eruption '}>news</Link></li>
                    <li><Link to={'/news/detail/120/ ice melt '}>News 2</Link></li>
                </ul>
                <Link to={'/'} >
                    <button>Back to the home page</button>
                </Link>
            </React.Fragment>)}}export default Index
Copy the code

Details page

import  React from 'react'
import {Link} from 'react-router-dom'


class Index extends  React.Component {
    componentDidMount() {
        console.log(this.props,'Parameter Information')}render() {
        return (
            <React.Fragment>
                <div>News Details Page</div>
            </React.Fragment>)}}export default Index
Copy the code

3.3 Not sure how many parameters to jump to with this.props. History

<li onClick={() = >{
                        this.props.history.push({
                            pathname: '/news/detail'.search:'id=119&title= solar flare '.query: {
                                id: 119.title: 'Solar flare'})}}> News 3 </li>Copy the code

To prevent query refresh arguments from being lost, pass search, and then encapsulate a method to search string as an object in the form of utils.js

export function localParam (search, hash) {
    search = search || window.location.search;
    hash = hash || window.location.hash;
    var fn = function(str, reg) {
        if (str) {
            var data = {};
            str.replace(reg, function($0, $1, $2, $3) {
                data[$1] = $3;
            });
            returndata; }};return {
        search : fn(search, new RegExp("([^? = &] +) (= (/ ^ & *))?"."g")) || {},
        hash : fn(hash, new RegExp("[[# ^ = &] +) (= (/ ^ & *))?"."g") | | {}}; }Copy the code
import  {localParam} from '.. /.. /assets/js/utils/index'
 console.log(this.props,'Parameter Information')
        console.log(localParam(this.props.location.search))
Copy the code

Simplify the push

  <li onClick={() = >{
                        this.props.history.push('/news/detail? Id =114&title= '}}> News 4 </li>Copy the code

The use of tools

 <React.Fragment>
                <div>News Details Page</div>

                <div>
                    {`ID: ${routeParams.id} Title: ${decodeURIComponent(routeParams.title)}`}
                </div>
                <button onClick={this.props.router.goBack.bind(this)}>Back to list page</button>
            </React.Fragment>
Copy the code

The effect