react-router-dom 6.0路由详解
React react-router-dom 6.0路由使用
由于react路由版本的更新迭代,记录路由知识点
新react-router-dom地址,点击查看详情。
下面为使用的例子
- Install
npm install react-router-dom@6 history@5
yarn add react-router-dom@6 history@5
- 配置路由地址
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
function Routelist(){
return(
<Router>
<Routes>
<Route path='/' element={<App />}></Route>
<Route path="invoices" element={<Invoices />}>
<Route
index
element={
<main style={{ padding: "1rem" }}>
<p>Select an invoice</p>
</main>
}
/>
<Route path=":invoiceId" element={<Invoice />} />
</Route>
{/* 不匹配 */}
<Route
path="*"
element={
<main style={{ padding: "1rem" }}>
<p>There's nothing here!</p>
</main>
}
/>
</Routes>
</Router>
)
}
在使用导航时需要特别注意的时,需要在父组件里面增加 <Outlet />
,才可以跳转成功。
-
跳转页面的方式
navigate(/invoices/${number}
, { state: 1 })<NavLink to={
/invoices/${number}
} state={{a:1}}>1在子组件中获取参数
import { useLocation } from 'react-router-dom'let location = useLocation() let data=location.state
地址栏参数获取
import { useParams } from 'react-router-dom'let params = useParams()
let data=params.get('参数名') -
在class components之前使用withRouter,但在新版中withRouter已移除,如果需要升级更新为 函数式组件或者封装hoc组件
eg:
import React from "react";
import { useParams, useLocation, useNavigate } from "react-router-dom";
function withRouter(Component) {
return (props) => (
<Component
{...props}
params={useParams()}
location={useLocation()}
navigate={useNavigate()}
/>
);
}
class Invoice extends React.Component {
render() {
return (
<div
onClick={() => this.props.navigate(`/invoices/1998`, { state: "1998" })}
>
22
</div>
);
}
}
export default withRouter(Invoice);
如有问题,不吝赐教,欢迎留言。