发布于 2026-01-06 0 阅读
0

如何使用 React Hooks - 详解两个最常用的 Hooks ✨

如何使用 React Hooks - 详解两个最常用的 Hooks ✨

嘿!

欢迎来到我的第一篇博文 :D。在这篇文章中,我将向你介绍 React Hooks,然后教你两个最常用的 Hook——状态Hook 和效果Hook。让我们马上开始吧!

什么是钩子?

Hooks 最早在 React v16.8 中引入。它允许你不用 JavaScript 类就能编写组件。这真的很棒,因为这意味着你可以在普通的 JavaScript 函数中使用状态、生命周期方法和其他强大的功能!

注意:编写类组件仍然完全没问题。React 目前没有弃用的计划。但是,Hooks 正逐渐成为编写 React 代码更高效的方式,所以我建议你尝试一下,相信你会爱上它的!

让我们来看一个使用类组件和钩子函数编写的简单组件:

// using Class Components
class CounterComponent extends React.Component {
  constructor() {
    super();

    this.state = {
      count: 0
    };
  }

  componentDidMount() {
    console.log("Component mounted");
  }

  componentDidUpdate(prevProps, prevState) {
    console.log("Component rendered");

    if (prevState.count !== this.state.count) {
      console.log("current count is", this.state.count);
    }
  }

  componentWillUnmount() {
    console.log("Unmounting the component...");
  }

  render() {
    return (
      <>
        <div>
          <button
            onClick={() => this.setState({ count: this.state.count + 1 })}
          >
            Increase
          </button>
          <button
            onClick={() => this.setState({ count: this.state.count - 1 })}
          >
            Decrease
          </button>
        </div>
        <div>
          <p>Current count: {this.state.count}</p>
        </div>
      </>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode
// using Hooks
const Counter = () => {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component mounted");
  }, []);

  useEffect(() => {
    console.log("Component rendered");
    return () => console.log("Unmounting the component...");
  });

  useEffect(() => {
    console.log("current count is", count);
  }, [count]);

  return (
    <>
      <div>
        <button onClick={() => setCount(count + 1)}>Increase</button>
        <button onClick={() => setCount(count - 1)}>Decrease</button>
      </div>
      <div>
        <p>Current count: {count}</p>
      </div>
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

正如我们所看到的,使用 hooks 编写的代码更加简洁,我们不必再担心“this”了。

为什么要用钩子?

React 类组件的代码压缩效果不佳,导致热重载不稳定。相比之下,JavaScript 函数的代码压缩效果要好得多。

此外,useEffect hook 整合了类组件的许多生命周期方法,例如 componentDidMount、componentDidUpdate 和 componentWillUnmount。这意味着我们不再需要将工作拆分到不同的方法中。

借助 hooks,通过创建自己的 hooks(称为自定义 hooks),可以轻松地重用有状态的逻辑。

React hooks 使我们的代码更简洁、更短,从而提供良好的开发体验!

useState Hook

此钩子的目的是允许你在函数式组件中使用状态。useState 声明的基本语法如下:

const [count, setCount] = useState(0);
Enter fullscreen mode Exit fullscreen mode

这里我声明了一个名为 `useState` 的状态变量count,并将其值设置为 0。要更新用户名,我们将调用setCount`useState` 函数。`useState` 函数总是返回两个值:一个状态变量和一个用于更新该状态变量的函数。

return (
<div>
  <button onClick={() => setCount(count + 1)}>Increase</button>
  <button onClick={() => setCount(count - 1)}>Decrease</button>
</div>
...
)
Enter fullscreen mode Exit fullscreen mode

要显示状态,我们直接使用count

return (
...
<div>
  <p>Current count: {count}</p>
</div>
)
Enter fullscreen mode Exit fullscreen mode

每当用户点击“增加”或“减少”按钮时,组件setCount都会更新count为新值,React 也会重新渲染该组件。让我们来看一下完整的组件:

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

  return (
  <>
    <div>
      <button onClick={() => setCount(count + 1)}>Increase</button>
      <button onClick={() => setCount(count - 1)}>Decrease</button>
    </div>
    <div>
      <p>Current count: {count}</p>
    </div>
  </>
  )
}
Enter fullscreen mode Exit fullscreen mode

您可以创建多个状态变量,并根据需要使用它们。

useEffect Hook

这个钩子允许你在函数式组件中使用生命周期方法,例如componentDidMount()componentDidUpdate()和。componentWillUnmount()

我们来看一个简单的例子:

useEffect(() => {
  // This runs at the first render and after every render by default
  console.log('Component rendered');

  // This runs just before React unmounts the component 
  return () => console.log('Unmounting the component...');
})
Enter fullscreen mode Exit fullscreen mode

如果您想控制某个 useEffect 的运行次数,可以指定第二个参数,即依赖数组,该数组包含 useEffect 的依赖值。useEffect 仅在依赖数组中至少有一个值自上次运行以来发生变化时才会运行。为了演示这一点,我们将使用之前的“计数”示例。让我们看看它是如何工作的:

useEffect(() => {
  console.log('current count is', count)
}, [count])
Enter fullscreen mode Exit fullscreen mode

如果传递一个空数组,useEffect 只会在挂载时运行一次:

useEffect(() => {
  console.log('Component mounted');
}, [])
Enter fullscreen mode Exit fullscreen mode

您可以通过此 codesandbox 链接查看完整代码

总而言之,Hooks 是编写 React 代码的强大工具。要开始使用 Hooks,你可以在创建新组件时就开始使用它。祝你编码愉快!

文章来源:https://dev.to/sushmita094/how-to-use-react-hooks-2-most-commonly-used-hooks-explained-3o3p