Context.js

import React from 'react'
const { Provider, Consumer } = React.createContext()
export { Provider, Consumer }

BrowserRouter.js

import React, { Component } from "react";
import { createBrowserHistory } from 'history'
import {Provider} from '../Context'

class BrowserRouter extends Component {
    constructor(props) {
        super(props)
        this.history = createBrowserHistory()
        this.state = {
            location: this.history.location,
        }
        this.unListen = this.history.listen(location => {
            this.setState({
                location
            })
        })
    }

    componentWillUnmount() {
        this.unListen && this.unListen()
    }
    render() {
        let value = {
            history:this.history,
            location:this.state.location
        }
        return (
            <Provider value={value}>
                {this.props.children}
            </Provider>
        )
    }
}
export default BrowserRouter

Route.js

import React, { Component } from 'react';
import {Consumer} from '../Context'
import pathToReg from "path-to-regexp";

class Route extends Component {
    render() {     
        return (
            <Consumer>
                {
                    vaule=>{
                        const {path,component:Component,exact=false}=this.props
                        let pathname=vaule.location.pathname
                        let keys=[]
                        const reg=pathToReg(path,keys,{end:exact})
                        let result=pathname.match(reg)
                        console.log(result)
                        keys=keys.map(item=>item.name)
                        let [url,...vaules]=result
                        console.log(keys)
                        let props={
                            history:vaule.history,
                            location:vaule.location,
                            match:{
                                params:keys.reduce((obj,current,index)=>{
                                    console.log(keys)
                                    obj[current]=vaules[index]
                                    console.log(obj)
                                    return obj
                                },{})
                            }

                        }
                        if(result){
                            return <Component {...props} />
                        }else{
                            return null
                        }
                       
                    }
                }
            </Consumer>
         
        );
    }
}

export default Route;

WARRIOR
25 声望3 粉丝