持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第5天,点击查看活动详情
今天开始一起学习分享 ahooks 的源码
ahooks是阿里巴巴出品的一套高质量可靠的 React Hooks 库
今天分享 第5个 hooks-useTitle
useTitle
首先看下 useTitle 的作用是什么
useTitle 的作用 是 用于设置页面标题。
接下来 看下 API
API
useTitle(title: string, options?: Options);
Params
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
title | 页面标题 | string | - |
Options
参数 | 说明 | 类型 | 默认值 |
---|---|---|---|
restoreOnUnmount | 组件卸载时,是否恢复上一个页面标题 | boolean | false |
只有1个参数,就是 要 设置的标题
有一个可选参数:restoreOnUnmount,表示组件卸载时,是否恢复上一个页面标题,类型是布尔值,默认值是false,表示组件卸载时,不恢复上一个页面的标题。
接下来 看下 用法
基本用法
设置页面标题
import React from 'react';
import { useTitle } from 'ahooks';
export default () => {
useTitle('Page Title');
return (
<div>
<p>Set title of the page.</p>
</div>
);
};
接下来一起看下 源码
源码
1.首先使用TypeScript定义 可选参数 restoreOnUnmount的类型,为布尔值
export interface Options {
restoreOnUnmount?: boolean;
}
2.然后定义默认参数restoreOnUnmount的初始值为false
const DEFAULT_OPTIONS: Options = {
restoreOnUnmount: false,
};
3.然后定义 useTitle 函数,传入两个参数,一个是要设置的标题title,另外一个参数是 可选的参数restoreOnUnmount
function useTitle(title: string, options: Options = DEFAULT_OPTIONS) {}
4.接着定义初始值,首先判断当前页面是否在可见状态,如果不是,则初始值设置为空,如果是,则默认取 当前页面的标题为初始值,这里使用useRef来记录标题的初始值,而不是用useState,为了就是在restoreOnUnmount为true时,恢复上一个页面的标题
import isBrowser from '../utils/isBrowser';
function useTitle(title: string, options: Options = DEFAULT_OPTIONS) {
const titleRef = useRef(isBrowser ? document.title : '');
}
- 使用 useEffect 来监听 title的变化,如果 title 变化 ,则重新将 title 赋值给 document.title
useEffect(() => {
document.title = title;
}, [title]);
6.使用useUnmount这个Hooks来监听页面是否要卸载,这个hooks我们后面再来分析。当监听到页面要卸载时,如果传入的参数restoreOnUnmount为true,我们就将页面的标题 恢复到上一个页面的标题
useUnmount(() => {
if (options.restoreOnUnmount) {
document.title = titleRef.current;
}
});