搜索
首页web前端js教程React 组件:类与函数式。

React Components: Class vs Functional.

我的 React 之旅始于四年前的函数式组件和 Hook。然后是“Siswe”,他是训练营的参与者,也是我们常驻班的组件爱好者。当我们其他人在使用功能组件的团队项目上进行协作时,“Siswe 坚定不移地忠诚于类组件。

组件是用户界面 (UI) 的构建块。

将它们视为乐高积木 - 您可以以各种方式组合它们来创建复杂的结构。它们是独立且可重用的代码片段,封装了 UI 和逻辑。

在另一个组件中重用一个组件通常如下所示:

import MyComponent from './MyComponent';

function ParentComponent() {
  return (
    <div>
      <mycomponent></mycomponent>
    </div>
  );
}

类组件和功能组件是在 React 中创建组件的两种主要方式。

import React, { Component } from 'react';

class Counter extends Component {
 constructor(props) {
  super(props);
  this.state = { count: 0 };
 }

 handleClick = () => {
  this.setState({  
 count: this.state.count + 1 });
 };

 render() {
  return  
 (
   <div>
    <p>You clicked {this.state.count} times</p>
    <button onclick="{this.handleClick}">Click me</button>
   </div>
  );
 }
}

export default Counter;

这是一个类组件,使用扩展 React.Component 类的 JavaScript 类创建。

import React, { useState } from 'react';

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

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onclick="{handleClick}">Click me</button>
    </div>
  );
}

export default Counter;

另一方面,这是一个函数组件,编写为简单的 JavaScript 函数。

状态管理:核心区别。

类组件使用 this.state 管理自己的内部状态。这通常在构造函数中初始化,使用 this.state 对象访问,并使用 this.setState 方法更新,如上面的代码块所示。

功能组件最初是无状态的。但随着 Hooks 的引入,他们获得了管理状态和生命周期逻辑的能力。利用 useState 挂钩来管理状态,它返回一对值:当前状态和更新它的函数,如上所示。这对于简单的状态管理来说已经足够了。对于涉及多个子值的更复杂的状态逻辑,或者当下一个状态依赖于前一个状态时,您需要使用 useReducer。
例如:

import React, { useReducer } from 'react';

const initialState = {
  count: 0,
  step: 1,
};

const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + state.step };
    case 'decrement':   

      return { ...state, count: state.count - state.step };
    case 'setStep':
      return { ...state, step: action.payload   
 };
    default:
      throw new Error();
  }
};

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

  const increment = () => dispatch({ type: 'increment' });
  const decrement = () => dispatch({ type: 'decrement'   
 });
  const setStep = (newStep) => dispatch({ type: 'setStep', payload: newStep });

  return (
    <div>
      <p>Count: {state.count}</p>
      <p>Step: {state.step}</p>
      <button onclick="{increment}">+</button>
      <button onclick="{decrement}">-</button>
      <input type="number" value="{state.step}" onchange="{(e)"> setStep(Number(e.target.value))} />
    </div>
  );
}

export default Counter;

这里,useReducer 以结构化且可维护的方式管理多个状态值和复杂的更新逻辑。 Hooks 专门用于功能组件。

避免直接操作两个组件中的状态对象。

无论组件类型如何,都不要直接修改或改变状态对象。相反,使用更新的值创建一个新对象。这种方法有助于 React 有效地跟踪更改并优化重新渲染。

功能组件示例:

import React, { useState } from 'react';

function UserProfile() {
  const [user, setUser] = useState({ name: 'Jane Doe', age: 30 });

  const handleNameChange = (newName) => {
    setUser({ ...user, name: newName }); // Create a new object with updated name
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <input type="text" value="{user.name}" onchange="{(e)"> handleNameChange(e.target.value)} />
    </div>
  );
}

export default UserProfile;

类组件示例:

import React, { Component } from 'react';

class UserProfile extends Component {
  state = { user: { name: 'Jane Doe', age: 30 } };

  handleNameChange = (newName) => {
    this.setState(prevState => ({
      user: { ...prevState.user, name: newName } // Create a new object with updated name
    }));
  };

  render() {
    return (
      <div>
        <p>Name: {this.state.user.name}</p>
        <p>Age: {this.state.user.age}</p>
        <input type="text" value="{this.state.user.name}" onchange="{(e)"> this.handleNameChange(e.target.value)} />
      </div>
    );
  }
}

export default UserProfile;

在这两个示例中,我们都在更新用户对象的 name 属性,同时保留原始对象的完整性。这确保了创建新的状态对象,保持不变性并防止状态更新的潜在问题。遵守这一点可确保可预测的行为、性能优化和更轻松的调试。

Class components are for complex logic.

  • Complex State Management: When dealing with intricate state logic that requires fine-grained control, class components with this.state and this.setState can offer more flexibility.
  • Lifecycle Methods: For components that heavily rely on lifecycle methods like componentDidMount, componentDidUpdate, or componentWillUnmount, class components are the traditional choice.
  • Error Boundaries: To handle errors within a component tree and prevent crashes, class components with componentDidCatch are essential.
  • Performance Optimization: In specific performance-critical scenarios, PureComponent or shouldComponentUpdate within class components can be leveraged.
  • Legacy Codebases: If you're working on an existing project that heavily relies on class components, it might be easier to maintain consistency by using them for new components.

Functional components are for simple views.

  • Simple Components: For presentational components with minimal state or logic, functional components are often the preferred choice due to their simplicity and readability.
  • State Management with Hooks: Leveraging useState and useReducer in functional components provides a powerful and flexible way to manage state.
  • Side Effects: The useEffect hook allows for managing side effects like data fetching, subscriptions, or manual DOM (document object model) manipulations.
  • Performance Optimization: useMemo and useCallback can be used to optimize performance in functional components.

Let your component's needs guide your decision.

The functional approach is generally considered more concise and readable, and it often suffices due to simplicity and efficiency. However, class components offer more control over state management and lifecycle methods, especially when dealing with intricate logic or performance optimization. This means better structure for organizing complex logic.

The choice between class and functional components is not always clear-cut, as there is no strict rule. Evaluate the requirements of your component and go with the type that aligns best with your project requirements.

Which component do you enjoy working with more?

以上是React 组件:类与函数式。的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
Python和JavaScript:了解每个的优势Python和JavaScript:了解每个的优势May 06, 2025 am 12:15 AM

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

JavaScript的核心:它是在C还是C上构建的?JavaScript的核心:它是在C还是C上构建的?May 05, 2025 am 12:07 AM

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript应用程序:从前端到后端JavaScript应用程序:从前端到后端May 04, 2025 am 12:12 AM

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

Python vs. JavaScript:您应该学到哪种语言?Python vs. JavaScript:您应该学到哪种语言?May 03, 2025 am 12:10 AM

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架:为现代网络开发提供动力JavaScript框架:为现代网络开发提供动力May 02, 2025 am 12:04 AM

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

JavaScript,C和浏览器之间的关系JavaScript,C和浏览器之间的关系May 01, 2025 am 12:06 AM

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr

node.js流带打字稿node.js流带打字稿Apr 30, 2025 am 08:22 AM

Node.js擅长于高效I/O,这在很大程度上要归功于流。 流媒体汇总处理数据,避免内存过载 - 大型文件,网络任务和实时应用程序的理想。将流与打字稿的类型安全结合起来创建POWE

Python vs. JavaScript:性能和效率注意事项Python vs. JavaScript:性能和效率注意事项Apr 30, 2025 am 12:08 AM

Python和JavaScript在性能和效率方面的差异主要体现在:1)Python作为解释型语言,运行速度较慢,但开发效率高,适合快速原型开发;2)JavaScript在浏览器中受限于单线程,但在Node.js中可利用多线程和异步I/O提升性能,两者在实际项目中各有优势。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

Atom编辑器mac版下载

Atom编辑器mac版下载

最流行的的开源编辑器