安装
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>
);
}
}