何时使用基于ES6类的React组件和功能性ES6 React组件?

JavaScript

古一Green

2020-03-11

After spending some time learning React I understand the difference between the two main paradigms of creating components.

My question is when should I use which one and why? What are the benefits/tradeoffs of one over the other?


ES6 classes:

import React, { Component } from 'react';

export class MyComponent extends Component {
  render() {
    return (
      <div></div>
    );
  }
}

Functional:

const MyComponent = (props) => {
    return (
      <div></div>
    );
}

I’m thinking functional whenever there is no state to be manipulated by that component, but is that it?

I’m guessing if I use any life cycle methods, it might be best to go with a class based component.

第561篇《何时使用基于ES6类的React组件和功能性ES6 React组件?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

2个回答
Green逆天 2020.03.11

从React 16.8开始,术语无状态功能组件具有误导性,应避免使用它们,因为它们不再不再是无状态的(React.SFC不推荐使用Dan Abramov on React.SFC),它们可以具有状态,可以具有钩子(充当钩子)生命周期方法),它们或多或少与类组件重叠

基于类的组件

功能组件:

为什么我更喜欢功能组件

  • 反应提供useEffect挂钩,是结合了非常清晰和简洁的方式componentDidMountcomponentDidUpdate以及componentWillUnmount生命周期方法
  • 使用钩子,您可以提取可以在组件之间轻松共享测试的逻辑
  • 减少范围界定上的混乱

反应动机为何使用挂钩(即功能组件)。

斯丁Jim 2020.03.11

尽可能尝试使用无状态功能(功能组件)。在某些情况下,您需要使用常规的React类:

  • 组件需要保持状态
  • 组件重新渲染过多,您需要通过以下方式进行控制 shouldComponentUpdate
  • 您需要一个容器组件

更新

现在有一个称为React的类PureComponent,您可以扩展(而不是Component)来实现它自己的方法shouldComponentUpdate,该方法可以为您比较浅道具。阅读更多

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android