跳转至

路由

Web分类

  • 静态页面:页面里的数据是写死的
  • 动态页面:页面里的数据是动态填充的
    • 后端渲染:数据在后端填充
    • 前端渲染:数据在前端填充

安装环境

  • VSCODE安装插件:Auto Import - ES6, TS, JSX, TSX
  • 安装Route组件:npm i react-router-dom

Route组件介绍

  • BrowserRouter:所有需要路由的组件,都要包裹在BrowserRouter组件内
  • Link:跳转到某个链接,to属性表示跳转到的链接
  • Routes:类似于C++中的switch,匹配第一个路径
  • Route:路由,path属性表示路径,element属性表示路由到的内容

URL中传递参数

解析URL:

1
<Route path="/linux/:chapter_id/:section_id/" element={<Linux />} />

获取参数,类组件写法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import React, { Component } from 'react';
import { useParams } from 'react-router-dom';

class Linux extends Component {
    state = {  } 
    render() {
        console.log(this.props.params);
        return <h1>Linux</h1>;
    }
}

export default (props) => (
    <Linux
        {...props}
        params={useParams()}
    />
)

函数组件写法:

1
2
3
4
5
6
7
8
9
import React, { Component } from 'react';
import { useParams } from 'react-router-dom';

const Linux = () => {
    console.log(useParams());
    return (<h1>Linux</h1>);
}

export default Linux;

Search Params传递参数

类组件写法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React, { Component } from 'react';
import { useSearchParams } from 'react-router-dom';

class Django extends Component {
    state = {
        searchParams: this.props.params[0],  // 获取某个参数
        setSearchParams: this.props.params[1],  // 设置链接中的参数,然后重新渲染当前页面
    }

    handleClick = () => {
        this.state.setSearchParams({
            name: "abc",
            age: 20,
        })
    }

    render() {
        console.log(this.state.searchParams.get('age'));
        return <h1 onClick={this.handleClick}>Django</h1>;
    }
}

export default (props) => (
    <Django
        {...props}
        params={useSearchParams()}
    />
);

函数组件写法:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import React, { Component } from 'react';
import { useSearchParams } from 'react-router-dom';

const Django = () => {
    let [searchParams, setSearchParams] = useSearchParams();
    console.log(searchParams.get('age'));
    return (<h1>Django</h1>);
}

export default Django;

重定向

使用Navigate组件可以重定向。

1
<Route path="*" element={ <Navigate replace to="/404" /> } />

嵌套路由

1
2
3
4
5
<Route path="/web" element={<Web />}>
    <Route index path="a" element={<h1>a</h1>} />
    <Route index path="b" element={<h1>b</h1>} />
    <Route index path="c" element={<h1>c</h1>} />
</Route>

注意:需要在父组件中添加<Outlet />组件,用来填充子组件的内容。