当前位置:首页 > React

react-hooks如何使用

2026-01-24 14:50:28React

使用 React Hooks 的基本方法

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>
  );
}
  • count 是状态变量,初始值为 0
  • setCount 是更新状态的函数。

useEffect

useEffect 用于处理副作用,如数据获取、订阅或手动 DOM 操作。

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>;
}
  • 第二个参数是依赖数组,控制 useEffect 的执行时机。

useContext

useContext 用于在组件中访问 React 的 Context。

import React, { useContext } from 'react';

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

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

  return <button style={{ background: theme === 'dark' ? '#333' : '#fff' }}>Click</button>;
}
  • ThemeContext 是一个 Context 对象。
  • useContext 直接获取当前 Context 的值。

useReducer

useReduceruseState 的替代方案,适用于复杂状态逻辑。

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>
  );
}
  • reducer 是一个纯函数,接收当前状态和动作,返回新状态。
  • dispatch 用于触发状态更新。

useRef

useRef 用于获取 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>
  );
}
  • inputRef 是一个可变的 ref 对象,其 current 属性指向 DOM 节点。

自定义 Hooks

自定义 Hooks 允许将组件逻辑提取到可重用的函数中。

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 DataDisplay() {
  const data = useFetch('https://api.example.com/data');

  return <div>{data ? data.message : 'Loading...'}</div>;
}
  • 自定义 Hook 以 use 开头命名,可以调用其他 Hooks。

注意事项

  • Hooks 只能在函数组件或自定义 Hooks 中调用。
  • 不要在循环、条件或嵌套函数中调用 Hooks。
  • 确保 Hooks 的调用顺序一致。

react-hooks如何使用

分享给朋友:

相关文章

react中monent如何获取日期

react中monent如何获取日期

使用 Moment.js 获取当前日期 在 React 中通过 Moment.js 获取当前日期,可以直接调用 moment() 函数。它会返回包含当前日期和时间的 Moment 对象。 impor…

如何构建react

如何构建react

构建 React 项目的步骤 安装 Node.js 和 npm 确保系统已安装 Node.js(包含 npm)。可通过命令行验证: node -v npm -v 使用 Create React Ap…

react路由如何使用

react路由如何使用

React 路由的基本使用 React 路由通常通过 react-router-dom 库实现,用于管理单页面应用(SPA)中的页面导航。 安装 react-router-dom: npm i…

如何实操react

如何实操react

安装 React 环境 使用 create-react-app 快速搭建项目: npx create-react-app my-app cd my-app npm start 项目启动后默认在…

react如何筛选数据

react如何筛选数据

筛选数据的方法 在React中筛选数据通常涉及对数组的操作,结合状态管理和渲染逻辑。以下是几种常见的实现方式: 使用数组的filter方法 通过JavaScript数组的filter方法筛选数据…

如何运行react项目

如何运行react项目

运行React项目的步骤 确保已安装Node.js(建议版本12或更高)和npm/yarn。若未安装,可从Node.js官网下载。 全局安装create-react-app脚手架工具(若已安装可跳…