MSIPO技术圈 首页 IT技术 查看内容

# 14 React 自定义Hook详解

2024-03-28

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

1. 使用状态管理数据

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. 使用生命周期

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. 订阅和取消订阅事件

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. 处理本地存储

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。

相关阅读

热门文章

    手机版|MSIPO技术圈 皖ICP备19022944号-2

    Copyright © 2024, msipo.com

    返回顶部