当前位置:首页 > 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 操作。

react-hooks如何使用

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 的替代方案,适用于复杂状态逻辑。

react-hooks如何使用

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 moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment 基本…

react 如何运行

react 如何运行

运行 React 项目的步骤 安装 Node.js 确保系统已安装 Node.js(建议版本 16+),可通过官网下载并安装。安装后验证版本: node -v npm -v 创建 React 项目…

react如何安装

react如何安装

安装React的步骤 确保已安装Node.js(建议版本12或更高),可通过以下命令检查版本: node -v npm -v 使用Create React App快速搭建项目(推荐): npx c…

react如何代码优化

react如何代码优化

减少不必要的重新渲染 使用 React.memo 包装函数组件以避免在 props 未变化时重新渲染。对于类组件,可以通过 shouldComponentUpdate 或继承 PureComponen…

react如何筛选数据

react如何筛选数据

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

react如何引用jquery

react如何引用jquery

在React项目中引用jQuery可以通过以下方法实现: 安装jQuery依赖 通过npm或yarn安装jQuery包: npm install jquery # 或 yarn add jquer…