何时使用基于 ES6 类的 React 组件与功能性 ES6 React 组件? [英] When to use ES6 class based React components vs. functional ES6 React components?

查看:29
本文介绍了何时使用基于 ES6 类的 React 组件与功能性 ES6 React 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在花了一些时间学习 React 之后,我理解了创建组件的两种主要范式之间的区别.

我的问题是我应该什么时候使用哪一个,为什么?一个相对于另一个的好处/权衡是什么?

<小时>

ES6 类:

import React, { Component } from 'react';导出类 MyComponent 扩展组件 {使成为() {返回 (<div></div>);}}

<小时>

功能性:

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

每当该组件没有要操作的状态时,我都认为它是函数式的,但就是这样吗?

我猜如果我使用任何生命周期方法,最好使用基于类的组件.

解决方案

您的想法是正确的.如果你的组件除了接收一些 props 和渲染之外,没有做更多的事情,那就去使用函数式的.您可以将它们视为纯函数,因为在给定相同的 props 的情况下,它们将始终呈现相同的行为.此外,他们不关心生命周期方法或拥有自己的内部状态.

因为它们是轻量级的,所以将这些简单的组件编写为功能组件是非常标准的.

如果您的组件需要更多功能,例如保持状态,请改用类.

更多信息:https://facebook.github.io/react/docs/reusable-components.html#es6-classes


编辑:在引入 React Hooks 之前,以上大部分内容都是正确的.

  • componentDidUpdate 可以用 useEffect(fn) 复制,其中 fn 是重新渲染时运行的函数.

  • componentDidMount 方法可以用 useEffect(fn, []) 复制,其中 fn 是重新渲染时运行的函数, 和 [] 是一个对象数组,组件将为其重新渲染,当且仅当自上次渲染以来至少有一个值发生了变化.由于没有,useEffect() 在第一次挂载时运行一次.

  • state 可以用 useState() 复制,其返回值可以解构为状态的引用和可以设置状态的函数(即,const [state, setState] = useState(initState)).一个例子可以更清楚地解释这一点:

const Counter = () =>{const [count, setCount] = useState(0)常量增量 = () =>{设置计数(计数 + 1);}返回 (<div><p>计数:{count}</p><button onClick={增量}>+</button>

)}默认导出计数器

顺便说一句,我听到很多人讨论出于性能原因不使用功能组件,特别是

<块引用>

事件处理函数在功能组件中为每个渲染重新定义"

虽然如此,但请考虑您的组件是否真的以如此值得关注的速度或体积渲染.

如果是,您可以使用 useCallbackuseMemo 钩子防止重新定义函数.但是,请记住,这可能会使您的代码(微观上)性能更差.

但老实说,我从未听说过重新定义函数是 React 应用程序的瓶颈.过早的优化是万恶之源——当它出现问题时要担心

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.

解决方案

You have the right idea. Go with functional if your component doesn't do much more than take in some props and render. You can think of these as pure functions because they will always render and behave the same, given the same props. Also, they don't care about lifecycle methods or have their own internal state.

Because they're lightweight, writing these simple components as functional components is pretty standard.

If your components need more functionality, like keeping state, use classes instead.

More info: https://facebook.github.io/react/docs/reusable-components.html#es6-classes


EDIT: Much of the above was true, until the introduction of React Hooks.

  • componentDidUpdate can be replicated with useEffect(fn), where fn is the function to run upon rerendering.

  • componentDidMount methods can be replicated with useEffect(fn, []), where fn is the function to run upon rerendering, and [] is an array of objects for which the component will rerender, if and only if at least one has changed value since the previous render. As there are none, useEffect() runs once, on first mount.

  • state can be replicated with useState(), whose return value can be destructured to a reference of the state and a function that can set the state (i.e., const [state, setState] = useState(initState)). An example might explain this more clearly:

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

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>+</button>
    </div>
  )
}

default export Counter

As a small aside, I have heard a number of people discussing not using functional components for the performance reasons, specifically that

"Event handling functions are redefined per render in functional components"

Whilst true, please consider if your components are really rendering at such a speed or volume that this would be worth concern.

If they are, you can prevent redefining functions using useCallback and useMemo hooks. However, bear in mind that this may make your code (microscopically) worse in performance.

But honestly, I have never heard of redefining functions being a bottleneck in React apps. Premature optimisations are the root of all evil - worry about this when it's a problem

这篇关于何时使用基于 ES6 类的 React 组件与功能性 ES6 React 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆