React

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > React > React类组件和函数组件

React类组件和函数组件的所有核心区别及说明

作者:英俊潇洒美少年

这篇文章主要介绍了React类组件和函数组件的所有核心区别及说明,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

一句话总结论

React 16 类组件:老写法,用 class、this、生命周期。

React 18 函数组件:新写法,用 Hooks,无 this,更简洁、性能更好。

一、最核心区别(必背)

对比React 16 类组件React 18 函数组件(Hooks)
写法class extends Componentfunction + Hooks
this必须用 this完全没有 this
状态this.state / this.setStateuseState
生命周期componentDidMount 等useEffect 一统天下
逻辑复用mixins / HOC / renderProps自定义 Hooks
代码量多、臃肿少、简洁
并发渲染不支持完美支持
性能一般更好

二、代码直接对比(一看就懂)

1. 定义组件

类组件(React 16)

import React from 'react'
class App extends React.Component {
  render() {
    return <div>hello</div>
  }
}

函数组件(React 18)

import React from 'react'
function App() {
  return <div>hello</div>
}

2. 状态(数据)

类组件

state = { count: 0 }

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

函数组件

import { useState } from 'react'
const [count, setCount] = useState(0)

const add = () => setCount(count + 1)

3. 发起请求(挂载时)

类组件(生命周期)

componentDidMount() {
  fetch('/api').then(res => res.json())
}

函数组件(useEffect)

useEffect(() => {
  fetch('/api').then(res => res.json())
}, [])

4. 监听数据变化

类组件

componentDidUpdate(prevProps) {
  if (prevProps.count !== this.props.count) {
    // 变化了
  }
}

函数组件

useEffect(() => {
  // 变化了
}, [count])

三、生命周期 VS Hooks(超级重要)

类组件的生命周期,全部可以被 useEffect 替代

类组件生命周期函数组件 Hooks
constructoruseState
componentDidMountuseEffect(..., [])
componentDidUpdateuseEffect(..., [依赖])
componentWillUnmountuseEffect 返回清理函数
shouldComponentUpdateReact.memo

一句话:

一个 useEffect 搞定类组件所有生命周期!

四、逻辑复用方式(天差地别)

类组件

只能用:

→ 代码嵌套多,嵌套地狱

函数组件

自定义 Hooks

function useCount() {
  const [count, setCount] = useState(0)
  return [count, setCount]
}

→ 干净、简洁、无嵌套、复用极强

五、性能与架构(React 18 关键)

类组件

函数组件(React 18)

六、最简单总结(面试必背)

类组件(React 16)

函数组件(React 18)

终极一句话

现在 React 开发,全部用函数组件+Hooks,类组件只用来维护老项目。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文