返回

React Hooks —— 状态管理篇

前端

绪论:

React Hooks 是 React 16.8 版本中引入的新特性,它允许函数组件使用 state 和其他 React 特性。函数组件是一种新的组件类型,它使用 JavaScript 函数来定义组件的行为,而不是使用 class。Hooks 使得函数组件能够具有与 class 组件相同的功能,从而简化了组件的编写。

使用 Hooks 管理状态:

useState Hook:

useState Hook 用于管理组件的 state。它接受一个初始值作为参数,并返回一个包含当前 state 值和一个更新 state 的函数的数组。当组件重新渲染时,state 的值将被更新。

import React, { useState } from 'react';

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

  const incrementCount = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Current count: {count}</p>
      <button onClick={incrementCount}>Increment count</button>
    </div>
  );
}

export default Counter;

useEffect Hook:

useEffect Hook 用于在组件渲染后执行某些副作用。它接受两个参数:一个函数和一个依赖项数组。函数将在组件渲染后立即执行,并且当依赖项数组中的任何一个值发生变化时,该函数将再次执行。

import React, { useEffect } from 'react';

function MyComponent() {
  useEffect(() => {
    // This function will be called after the component is rendered
    console.log('Component rendered');
  }, []);

  return (
    <div>
      <p>MyComponent</p>
    </div>
  );
}

export default MyComponent;

useContext Hook:

useContext Hook 用于在组件之间共享数据。它接受一个 context 对象作为参数,并返回该 context 对象的当前值。当 context 对象的值发生变化时,组件将重新渲染。

import React, { useContext } from 'react';

const MyContext = React.createContext(null);

function MyComponent() {
  const contextValue = useContext(MyContext);

  return (
    <div>
      <p>MyComponent: {contextValue}</p>
    </div>
  );
}

export default MyComponent;

总结:

Hooks 是 React 16.8 版本中引入的新特性,它允许函数组件使用 state 和其他 React 特性。useState Hook 用于管理组件的 state,useEffect Hook 用于在组件渲染后执行某些副作用,useContext Hook 用于在组件之间共享数据。Hooks 简化了组件的编写,使得函数组件能够具有与 class 组件相同的功能。