第8章 Hook,路由,与 URL 状态管理
# ⽤useRef实现useDocumentTitle - useRef与Hook 闭包详解
闭包与React hook 可看我另外一篇文章《react hook 与 闭包》
// src/screens/project-list/index.tsx
import { useDebounce, useDocumentTitle } from "../../utils";
...
export const ProjectListScreen = () => {
useDocumentTitle('项目列表', false)
...
// src/utils/index.ts
export const useDocumentTitle = (
title: string,
keepOnUnmount: boolean = true
) => {
const oldTitle = useRef(document.title).current;
// 页面加载时: 旧title
// 加载后:新title
useEffect(() => {
document.title = title;
}, [title]);
useEffect(() => {
return () => {
if (!keepOnUnmount) {
// 如果不指定依赖,读到的就是旧title
document.title = oldTitle;
}
};
}, [oldTitle, keepOnUnmount]);
};
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
29
30
31
32
33
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
29
30
31
32
33
# 添加项目列表和项目详情路由
# 安装react-router
yarn add react-router -S
# 使用
// src/authenticated-app.tsx
import { Routes, Route } from "react-router";
...
export const AuthentictedApp = () => {
return (
<Container>
<PageHeader></PageHeader>
<Routes>
<Route path='/project' element={<ProjectListScreen />} />
<Route path='/project/:projectId/*' element={<ProjectScreen />} />
</Routes>
</Container>
);
};
...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
新增项目详情页面
// src/authenticated-app.tsx
...
import { ProjectScreen } from "screens/project";
...
// src/screens/project/index.tsx
import React from "react"
export const ProjectScreen = () => {
return <div>project</div>
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
上次更新: 2022/08/14, 18:25:44