当前位置:首页 > React

react hooks实现

2026-01-26 13:35:55React

React Hooks 是 React 16.8 引入的特性,允许在函数组件中使用状态和其他 React 特性,而无需编写类组件。以下是常见 Hooks 的实现方式和用法示例。

useState

useState 用于在函数组件中管理局部状态。它返回一个状态值和一个更新状态的函数。

import React, { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

useEffect

useEffect 用于处理副作用,如数据获取、订阅或手动修改 DOM。它可以模拟类组件的 componentDidMountcomponentDidUpdatecomponentWillUnmount

import React, { useState, useEffect } from 'react';

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // 空依赖数组表示仅在组件挂载时运行

  return <div>{data ? data.message : 'Loading...'}</div>;
}

useContext

useContext 用于在组件中访问 React 的 Context,避免多级 props 传递。

import React, { useContext } from 'react';

const ThemeContext = React.createContext('light');

function ThemedButton() {
  const theme = useContext(ThemeContext);

  return <button className={theme}>Themed Button</button>;
}

useReducer

useReduceruseState 的替代方案,适用于复杂状态逻辑。它接受一个 reducer 函数和初始状态,返回当前状态和 dispatch 函数。

import React, { useReducer } from 'react';

const initialState = { count: 0 };

function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
}

function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </div>
  );
}

useRef

useRef 返回一个可变的 ref 对象,其 .current 属性初始化为传入的参数。常用于访问 DOM 节点或存储可变值。

import React, { useRef } from 'react';

function TextInput() {
  const inputRef = useRef(null);

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

自定义 Hook

自定义 Hook 可以将组件逻辑提取到可重用的函数中。自定义 Hook 的名称必须以 use 开头。

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    fetch(url)
      .then(response => response.json())
      .then(data => setData(data));
  }, [url]);

  return data;
}

function UserProfile() {
  const user = useFetch('https://api.example.com/user');

  return <div>{user ? user.name : 'Loading...'}</div>;
}

注意事项

  • Hooks 只能在函数组件的顶层调用,不能在循环、条件或嵌套函数中使用。
  • Hooks 的调用顺序必须保持一致,确保 React 能正确追踪状态。
  • 自定义 Hook 内部可以调用其他 Hooks,但必须遵循 Hooks 的规则。

react hooks实现

标签: reacthooks
分享给朋友:

相关文章

react如何取消渲染

react如何取消渲染

取消渲染的方法 在React中,取消渲染通常指阻止组件在特定条件下进行不必要的渲染。可以通过以下几种方式实现: 条件渲染 使用条件语句(如if或三元运算符)直接返回null,避免渲染组件内容。例如:…

react native 如何

react native 如何

React Native 开发基础 React Native 是一个用于构建跨平台移动应用的框架,允许开发者使用 JavaScript 和 React 编写代码,同时生成原生 iOS 和 Androi…

react如何更新

react如何更新

更新 React 版本的方法 检查当前 React 版本 运行以下命令查看项目中安装的 React 版本: npm list react 更新 React 及相关依赖 通过 npm 或 yarn…

react性能如何

react性能如何

React 性能特点 React 通过虚拟 DOM(Virtual DOM)和高效的 diff 算法优化性能。虚拟 DOM 减少了直接操作真实 DOM 的开销,仅在必要时更新变化的部分。React 的…

react如何运行

react如何运行

运行React项目的步骤 安装Node.js 确保系统已安装Node.js(建议版本12以上),可从官网下载并安装。Node.js自带npm包管理器,用于后续依赖安装。 创建React项目 使用官…

react如何收录

react如何收录

React 收录方法 React 的收录主要涉及搜索引擎优化(SEO)和预渲染技术。由于 React 是单页应用(SPA),默认情况下内容由 JavaScript 动态生成,可能导致搜索引擎爬虫难以收…