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.
从React 16.8开始,术语无状态功能组件具有误导性,应避免使用它们,因为它们不再不再是无状态的(React.SFC不推荐使用,Dan Abramov on React.SFC),它们可以具有状态,可以具有钩子(充当钩子)生命周期方法),它们或多或少与类组件重叠
基于类的组件
功能组件:
为什么我更喜欢功能组件
componentDidMount
,componentDidUpdate
以及componentWillUnmount
生命周期方法反应动机为何使用挂钩(即功能组件)。