Skip to content

react-router-dom 6.0路由详解 #1

Description

@JoeXin

React react-router-dom 6.0路由使用

由于react路由版本的更新迭代,记录路由知识点

react-router-dom地址,点击查看详情。

下面为使用的例子

  1. Install
   npm install react-router-dom@6 history@5

   yarn add react-router-dom@6 history@5

  1. 配置路由地址
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 /> ,才可以跳转成功。
  1. 跳转页面的方式
    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('参数名')

  2. 在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);

如有问题,不吝赐教,欢迎留言。

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions