【React进阶】一文带你了解Hooks用法

100 阅读2分钟

React Hooks是React 16.8中引入的新特性,它允许在函数组件中使用状态和生命周期特性。以下是一些常用的React Hooks及其用法和案例:

  1. useState:用于在函数组件中声明和操作状态。

const [state, setState] = useState(initialState);

import React, { useState } from 'react';

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

  return (
    <div>
      <p>当前计数:{count}</p>
      <button onClick={() => setCount(count + 1)}>加1</button>
    </div>
  );
}

export default Counter;
  1. useEffect:用于在函数组件中处理副作用,如数据获取、订阅、定时器等。

useEffect(() => { /* 副作用操作 */ }, [依赖项数组]);

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

function UserInfo({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`https://api.example.com/users/${userId}`);
      const userData = await response.json();
      setUser(userData);
    };

    fetchData();
  }, [userId]);

  return (
    <div>
      {user ? (
        <div>
          <h1>{user.name}</h1>
          <p>Email: {user.email}</p>
        </div>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}
export default UserInfo;
  1. useContext:用于在函数组件中访问上下文(Context)的值。

const contextValue = useContext(Context);

import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';

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

  return (
    <button style={{ background: theme.background, color: theme.foreground }}>
      主题按钮
    </button>
  );
}
export default ThemedButton;
  1. useReducer:用于在函数组件中处理更复杂的状态逻辑。

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

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>当前计数:{state.count}</p>
      <button onClick={() => dispatch({ type: 'increment' })}>加1</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>减1</button>
    </div>
  );
}
export default Counter;
  1. useMemo 用来缓存计算结果,避免重复计算。它接收一个函数和一个依赖数组作为参数,只有依赖数组发生变化时,才会重新计算函数的返回值。下面是一个计算斐波那契数列的例子:
import { useMemo } from 'react';

function Fibonacci({ n }) {
  const result = useMemo(() => {
    if (n === 1 || n === 2) {
      return 1;
    }
    let a = 1, b = 1;
    for (let i = 3; i <= n; i++) {
      let c = a + b;
      a = b;
      b = c;
    }
    return b;
  }, [n]);

  return <div>{result}</div>;
}
  1. useCallback 用来缓存函数,避免重复创建。它接收一个函数和一个依赖数组作为参数,只有依赖数组发生变化时,才会重新创建函数。下面是一个在点击按钮时更新计数器的例子:
import { useState, useCallback } from 'react';

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

  const handleClick = useCallback(() => {
    setCount(count => count + 1);
  }, []);

  return (
    <div>
      <div>Count: {count}</div>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
}
  1. useRef 用来保存可变值,类似于类组件中的实例变量。它返回一个对象,该对象的 current 属性可以被赋值和读取。下面是一个在定时器中使用 useRef 的例子:
import { useRef, useEffect } from 'react';

function Timer() {
  const intervalRef = useRef(null);
  const [count, setCount] = useState(0);

  useEffect(() => {
    intervalRef.current = setInterval(() => {
      setCount(count => count + 1);
    }, 1000);
    return () => clearInterval(intervalRef.current);
  }, []);

  return <div>{count}</div>;
}