# 14 React 自定义Hook详解

自定义 Hook 是一个函数,其名称以 "use" 开头,函数内部可以调用其他 Hook。自定义 Hook 是一个函数,其名称以 "use" 开头,函数内部可以调用其他 Hook。下面是几个自定义 Hook 的例子以及需要注意的知识:

1. 使用状态管理数据

javascript 复制代码
import { useState } from 'react';

function useCounter(initialValue, step) {
  const [count, setCount] = useState(initialValue);

  const increment = () => setCount(count + step);
  const decrement = () => setCount(count - step);

  return { count, increment, decrement };
}

// 在组件中使用
function Counter() {
  const { count, increment, decrement } = useCounter(0, 1);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

注意:

  • 自定义 Hook 可以帮助复用状态逻辑。
  • 在使用状态时,确保传递正确的默认值和参数。

2. 使用生命周期

javascript 复制代码
import { useState, useEffect } from 'react';

function useDocumentTitle(title) {
  useEffect(() => {
    document.title = title;

    return () => {
      document.title = 'React App'; // 在卸载时重置标题
    };
  }, [title]);
}

// 在组件中使用
function TitleUpdater() {
  useDocumentTitle('New Title');

  return <div>Updating Document Title</div>;
}

注意:

  • useEffect 用于处理副作用,如修改文档标题。
  • 注意 useEffect 的第二个参数,这决定了何时应该重新执行副作用。

3. 订阅和取消订阅事件

javascript 复制代码
import { useEffect } from 'react';

function useEventListener(eventName, handler) {
  useEffect(() => {
    const eventListener = (event) => handler(event);
    window.addEventListener(eventName, eventListener);

    return () => {
      window.removeEventListener(eventName, eventListener);
    };
  }, [eventName, handler]);
}

// 在组件中使用
function EventListenerComponent() {
  const handleScroll = (event) => {
    console.log('Scrolled:', event);
  };

  useEventListener('scroll', handleScroll);

  return <div>Listening to Scroll Events</div>;
}

注意:

  • useEffect 在这里用于添加和移除事件监听器。
  • 注意清除函数,以免内存泄漏。

4. 处理本地存储

javascript 复制代码
import { useState } from 'react';

function useLocalStorage(key, initialValue) {
  const [value, setValue] = useState(() => {
    const storedValue = localStorage.getItem(key);
    return storedValue ? JSON.parse(storedValue) : initialValue;
  });

  const updateValue = (newValue) => {
    setValue(newValue);
    localStorage.setItem(key, JSON.stringify(newValue));
  };

  return [value, updateValue];
}

// 在组件中使用
function LocalStorageComponent() {
  const [name, setName] = useLocalStorage('name', '');

  const handleChange = (event) => {
    setName(event.target.value);
  };

  return (
    <div>
      <input type="text" value={name} onChange={handleChange} />
      <p>Hello, {name}!</p>
    </div>
  );
}

注意:

  • 使用 useState 和 useEffect 来管理本地存储。
  • 注意对存储数据进行序列化和反序列化。

注意事项:

  • 自定义 Hook 本质上是函数,但需要符合特定的命名规范以及 Hook 规则。
  • 在自定义 Hook 内部,可以使用其他 Hook,但不要在普通 JavaScript 函数中调用 Hook。
相关推荐
SailingCoder23 分钟前
【封闭结束1】端到端交付:Agent 一次请求如何走完全链路
前端·安全·ai·面试·agent·harness
风骏时光牛马2 小时前
AI多模块协同自动化工作流
前端
zhangminghuan3 小时前
前端面试应对技巧
前端·面试·职场和发展
计算机魔术师3 小时前
潜伏14年的PHP致命洞,AI跑两天就交卷了
前端
IT_陈寒3 小时前
Vue的这个响应式陷阱我居然现在才发现
前端·人工智能·后端
Python自动化直播4 小时前
智能脚本批量管理拆开看:导入、导出、重写、试听
前端·python·ai·秒播
开开心心就好4 小时前
发票信息录入太麻烦?离线工具一键转表格
运维·服务器·前端·pdf·ocr·maven·intellij-idea
এ慕ོ冬℘゜5 小时前
ES Promise.all/ Promise.race
前端·javascript·elasticsearch
喜欢打篮球的普通人6 小时前
LLVM 前端与优化层:Clang 如何把 C 代码变成 IR
c语言·前端·状态模式