• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

自定义hook创建使用

武飞扬头像
yiranlater
帮助1

自定义 Hook 使用原则

  • 自定义 Hook 必须以 "use" 开头,这是一个约定俗成的规则,能帮助我们更容易地识别其作为 Hook 的使用方式。
  • 在自定义 Hook 中只能在最顶层调用其他 Hook。不能在循环、条件或嵌套函数中调用 Hook。

1. useFetch - 用于进行异步数据请求

import { useState, useEffect } from 'react';

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch(url);
      const data = await response.json();
      setData(data);
      setLoading(false);
    }
    fetchData();
  }, [url]);

  return { data, loading };
}

然后你可以在组件中这样使用:

jsx复制代码
function App() {
  const { data, loading } = useFetch('https://api.example.com/data');

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    // render your component with data
  );
}

2. useFormInput - 用于处理表单输入字段

import { useState } from 'react';

function useFormInput(initialValue) {
  const [value, setValue] = useState(initialValue);

  function handleChange(e) {
    setValue(e.target.value);
  }

  return {
    value,
    onChange: handleChange,
  };
}

然后你可以在组件中这样使用:

function Form() {
  const name = useFormInput('');
  const password = useFormInput('');

  return (
    <form>
      <input type="text" {...name} placeholder="Name" />
      <input type="password" {...password} placeholder="Password" />
    </form>
  );
}

3. useLocalStorage - 用于处理本地存储

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.log(error);
      return initialValue;
    }
  });

  const setValue = value => {
    try {
      const valueToStore =
        value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      window.localStorage.setItem(key, JSON.stringify(valueToStore));
    } catch (error) {
      console.log(error);
    }
  };

  return [storedValue, setValue];
}

然后你可以在组件中这样使用:

function Counter() {
  const [count, setCount] = useLocalStorage('count', 0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count   1)}>
        Click me
      </button>
    </div>
  );
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /boutique/detail/tanhgajchc
系列文章
更多 icon
同类精品
更多 icon
继续加载