返回

深入掌握 React Hooks,自定义构建常用 Hooks

前端

前言

上一篇文章《一文归纳 React Hooks 常用场景》,我们按照使用场景举例说明,帮助您初步理解并熟练运用 React Hooks 的大部分特性。在这篇文章中,我们将更进一步,通过自定义一些 Hooks,解决您在日常项目中非常常见的需求场景,做到代劳与复用,让您的开发更高效。

自建 Hook 场景与实践

场景 1:控制组件生命周期

例如:想要在组件卸载时执行一些操作。

// 自定义 Hook
import { useEffect } from "react";
const useUnmount = (fn) => {
  useEffect(() => {
    return fn;
  }, []);
};

在组件中使用:

import { useUnmount } from "./useUnmount";

const Component = () => {
  const sayBye = () => {
    console.log("Bye!");
  };
  useUnmount(sayBye);
  return <div>Component</div>;
};

场景 2:表单数据双向绑定

例如:在表单中使用双向数据绑定,确保表单数据与组件状态同步。

// 自定义 Hook
import { useState } from "react";
const useForm = (initialValues) => {
  const [values, setValues] = useState(initialValues);
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setValues({ ...values, [name]: value });
  };
  return { values, handleInputChange };
};

在组件中使用:

import { useForm } from "./useForm";

const Component = () => {
  const { values, handleInputChange } = useForm({ name: "", email: "" });
  return (
    <form>
      <input type="text" name="name" value={values.name} onChange={handleInputChange} />
      <input type="email" name="email" value={values.email} onChange={handleInputChange} />
      <button type="submit">Submit</button>
    </form>
  );
};

场景 3:网络请求

例如:在组件中进行网络请求,并管理请求状态。

// 自定义 Hook
import { useState, useEffect } from "react";
const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(url);
        const data = await response.json();
        setData(data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [url]);
  return { data, loading, error };
};

在组件中使用:

import { useFetch } from "./useFetch";

const Component = () => {
  const { data, loading, error } = useFetch("https://example.com/api/data");
  return (
    <>
      {loading ? <div>Loading...</div> : <div>{data.message}</div>}
      {error ? <div>{error.message}</div> : null}
    </>
  );
};

总结

本文中介绍了 React Hooks 的自定义使用方法,并通过三个具体的场景和实例进行了解释和演示。希望这些内容能帮助您在项目中更熟练地运用 React Hooks,以提高开发效率和代码质量。