React Hooks 是 React 16.8 版本引入的新特性,它允许你在不编写类的情况下使用 state 和其他 React 特性。本教程将带你深入了解 React Hooks 的使用方法和最佳实践。

安装 React

在开始之前,请确保你已经安装了 React。你可以通过以下命令安装:

npx create-react-app my-app
cd my-app
npm start

基础 Hooks

useState

useState 是 React 中最常用的 Hook,它允许你在函数组件中添加 state。

import React, { useState } from 'react';

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

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

useEffect

useEffect 允许你在组件中执行副作用操作,例如数据获取、订阅或手动更改 DOM。

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

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

  useEffect(() => {
    fetch('/api/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // 空数组意味着这个 effect 只在组件挂载时运行一次

  if (!data) return <div>Loading...</div>;

  return (
    <div>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

高级 Hooks

useContext

useContext 允许你订阅一个 context,并使用其值。

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

function Component() {
  const value = useContext(MyContext);
  return <div>{value}</div>;
}

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 (
    <>
      Count: {state.count}
      <button onClick={() => dispatch({ type: 'increment' })}>+</button>
      <button onClick={() => dispatch({ type: 'decrement' })}>-</button>
    </>
  );
}

扩展阅读

想要了解更多关于 React Hooks 的知识,可以阅读官方文档:React Hooks Documentation

React Hooks