R

React 中的基本 Hooks React 中 Hooks 的优势 React 中的基本 Hooks

2025-06-10

React 中的基本 Hooks

React Hooks 的优势

React 中的基本 Hooks

继我上一篇文章《React 中的 Hooks》获得热烈反响后,我兑现承诺,带着React 系列文章的第二篇回归了。您可以点击此处查看。在上一篇文章中,我们讨论了什么是 Hooks 以及它们的工作原理。而本文将重点介绍一些实例,并讨论一些 React 的基本 Hooks。

自 React 引入 Hooks 以来,它已经发挥了不少作用。首先,我们来讨论一下 Hooks 的优势。

React Hooks 的优势

  • 更易于测试和使用
  • 它们避免了处理 HOC、渲染 props、子元素作为函数和类
  • 使用 Hooks 后代码可读性更强,并且关注点也更加独立
  • 更好的代码修改 - 由于 Hooks 是函数,因此代码的修改更好,因为 JavaScript 中的函数修改比类要好得多
  • 钩子还可以避免生命周期方法和组件之间的重复逻辑

以上分享的优点只是从无数优点中精选出来的一些。现在让我们进入讨论的正题,即 React 中的基础 Hooks。

一般来说,React 中的 Hook 可以分为几个内置 Hook,包括 03 基本 Hook 和 07 附加 Hook。这里我们将讨论 React 的基本 Hook。

React 中的基本 Hooks

在 React 中可以使用三个(03)个基本 Hook。它们是:

  1. useState
  2. useEffect
  3. 使用上下文

useState()

useState Hooks,或 Hooks State,是 React 应用中声明状态的新方式。Hook 使用 useState() 函数组件来设置和检索状态。在初始渲染期间,返回的状态 (state) 与作为第一个参数传递的值 (initialState) 相同。它可以声明为
const [state, setState] = useState(initialState);

setState 函数用于更新状态。它接受新的状态值并加入组件的重新渲染队列。用户/开发者可以这样使用 setState 函数:
setState(newState);

先决条件

在使用 setState 函数之前,必须先从 React 导入 useState。具体方法如下:

import React, { useState } from 'react';
Enter fullscreen mode Exit fullscreen mode

让我们通过以下示例来理解 Hook State:

import React, { useState } from 'react';  

function CountApp() {  
  // Declare a new state variable, which we'll call "count"  
  const [count, setCount] = useState(0);  

  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CountApp;  
Enter fullscreen mode Exit fullscreen mode

替代文本
在上面的例子中,useState 是一个 Hook,需要在函数组件内部调用它来添加一些本地状态。useState 返回一个值对,其中第一个元素是当前状态值/初始值,第二个元素是一个允许我们更新它的函数。然后,我们可以从事件处理程序或其他位置调用此函数。useState 类似于类中的 this.setState。不使用 Hook 的等效代码如下所示:

import React, { useState } from 'react';  

class CountApp extends React.Component {  
  constructor(props) {  
    super(props);  
    this.state = {  
      count: 0  
    };  
  }  
  render() {  
    return (  
      <div>  
        <p><b>You clicked {this.state.count} times</b></p>  
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>  
          Click me  
        </button>  
      </div>  
    );  
  }  
}  
export default CountApp;  
Enter fullscreen mode Exit fullscreen mode

useEffect()

继 State Hooks 之后,Reac 中最基本的 Hook 是 Effect Hook。它允许我们在函数式组件中执行副作用(在 Action 中)。它不使用类组件中可用的组件生命周期方法。在引入 Hooks 之前,它类似于使用componentDidMount(), componentDidUpdate(), componentWillUnmount()生命周期方法。useEffects() 允许 Web 开发者使其 Web 应用程序无缝地执行某些操作。例如:

  • 更新 DOM
  • 从服务器 API 获取并使用数据
  • 设置订阅等。换句话说,useEffect 接受一个函数,该函数用于在函数中引起效果。
useEffect(
    () => {
        const subscription = props.source.subscribe();
        return () => {
            subscription.unsubscribe();
        };
    },
    [props.source],
);
Enter fullscreen mode Exit fullscreen mode

注意:如果希望函数仅运行一次,则可以将第二个参数作为空数组传递

现在,让我们看一段细长且实用的代码块,以进一步理解 useEffect() 的用法。但在此之前,就像 useState 一样,我们必须从 React 导入 useEffect。例如:
import React, { useState, useEffect } from 'react';
现在,让我们通过以下示例来理解 Hook Effect:

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

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

  // Similar to componentDidMount and componentDidUpdate:  
  useEffect(() => {  
    // Update the document title using the browser API  
    document.title = `You clicked ${count} times`;  
  });  

  return (  
    <div>  
      <p>You clicked {count} times</p>  
      <button onClick={() => setCount(count + 1)}>  
        Click me  
      </button>  
    </div>  
  );  
}  
export default CounterExample;  
Enter fullscreen mode Exit fullscreen mode

替代文本
上面的代码示例继承了上一个 useState() 示例,并添加了一个新功能,即将文档标题设置为自定义消息,其中包含点击次数。React
中有两种类型的效果钩子,分别是:

  1. 无需清理的效果
  2. 清理的效果我们将在下一篇文章中讨论这些。

使用上下文()

useContext 接受一个 context 对象,即 React.createContext 返回的值,并返回该 context 的当前 context 值。调用 useContext 的组件在 context 值发生变化时总会重新渲染。

换句话说,useContext() hook 用于创建可在整个组件层次结构中访问的通用数据,而无需手动将 props 传递到每个级别。定义的 Context 将可供所有子组件使用,而无需涉及“props”。

在跳过 useContext 的示例之前,让我们先看一个示例代码,不使用 useContext,即使用 Consumer 组件(困难的方式):

import React from "react";
import ReactDOM from "react-dom";

// Create a Context
const NumberContext = React.createContext();
// It returns an object with 2 values:
// { Provider, Consumer }

function App() {
  // Use the Provider to make a value available to all
  // children and grandchildren
  return (
    <NumberContext.Provider value={42}>
      <div>
        <Display />
      </div>
    </NumberContext.Provider>
  );
}

function Display() {
  // Use the Consumer to grab the value from context
  // Notice this component didn't get any props!
  return (
    <NumberContext.Consumer>
      {value => <div>The answer is {value}.</div>}
    </NumberContext.Consumer>
  );
}

ReactDOM.render(<App />, document.querySelector("#root"));
Enter fullscreen mode Exit fullscreen mode

让我们了解一下刚刚发生的事情。

首先,我们创建一个新的 context,并将其存储在 NumberContext 中。这是一个包含两个属性的对象:Provider 和 Consumer。它们是一对匹配的属性,并且天生就知道如何相互通信(但不知道如何与其他 context 通信)。

然后,我们渲染 NumberContext.Provider 并传入一些内容,并向其传递一个值属性。它会将该值提供给其所有后代及其后代。整个子树将能够使用 Consumer(或 useContext)来读取该值。

最后,我们用 Display 组件里面的 Consumer 读取值。

useContext() 代码示例

useContext() 让你无需消费者即可“使用”上下文。让我们用 useContext hook 重写 Display 组件:

// import useContext (or we could write React.useContext)
import React, { useContext } from 'react';

// ...

function Display() {
  const value = useContext(NumberContext);
  return <div>The answer is {value}.</div>;
}
Enter fullscreen mode Exit fullscreen mode

调用 useContext(),传入从 React.createContext 获取的 context 对象,然后弹出值。是不是很简单?但唯一需要注意的是,你必须将整个 context 对象传递给 useContext,而不仅仅是 Consumer!(这就是我没有立即解构 Context 对象的原因)React 最棒的地方在于,如果你忘记了,它会发出警告。

今天的文章就到这里。在上一篇文章中,我忘了提到我的导师,是他们教我学习 React。他们是Tahir MasoodZohaad Afzal

在下一篇文章中,我们将介绍 useEffect() 的类型,并尝试进一步深入了解 React 的超酷世界。

鏂囩珷鏉ユ簮锛�https://dev.to/mursalfk/basic-hooks-in-react-4ai3
PREV
开发人员应避免的 CSS 实践
NEXT
我试用了 Frontend Mentor 一周。什么是 Frontend Mentor?优点缺点提示我的使用体验