react-router-dom v6 的基本使用

安装
npm install react-router-dom

修改index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {BrowserRouter} from 'react-router-dom'

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <App/>
        </BrowserRouter>
    </React.StrictMode>,
    document.getElementById('root')
)

路由匹配

import React, {Component} from "react"
import {Route, Routes, Navigate, NavLink} from 'react-router-dom'
import FirstIndex from "./component/FirstIndex/index"
import MultilevelRoute from "./component/MultilevelRoute/index"
import HistoryDemo from "./component/HistoryDemo/HistoryDemo"

export default class App extends Component {

    render() {
        return (
            <div className="App">
                <HistoryDemo></HistoryDemo>
                <div>
                    <NavLink to="/index">Test1</NavLink>
                    <NavLink to="/multilevelRoute">MultilevelRoute</NavLink>
                </div>
                <div>
                    {/* react-router-dom v5使用 <Switch></Switch>*/}
                    {/* react-router-dom v6使用 <Routes></Routes>*/}
                    <Routes>
                        {/* react-router-dom v5使用 component={Test1}*/}
                        {/* exact={true} 开启严格匹配*/}
                        <Route exact={true} path="/index" element={<FirstIndex></FirstIndex>}></Route>
                        {/* react-router-dom v6嵌套路由需要在path最后加”/*”*/}
                        <Route path="/multilevelRoute/*" element={<MultilevelRoute></MultilevelRoute>}></Route>
                        {/*
                            react-router-dom v5 默认页设置:
                            <Redirect to="/index"></Redirect>
                        */}
                        {/* react-router-dom v6 默认页设置 */}
                        <Route element={<Navigate to="/index"/>}></Route>
                    </Routes>
                </div>
            </div>
        );
    }
}
上一篇:Apache Spark机器学习.1.6 机器学习工作流和Spark pipeline


下一篇:JQuery笔记-通过tag、class、id获取指定的dom