React函数式组件的状态
React无状态组件
React的Component分为有状态的class component和无状态的function component, class component的好处是可以完全控制组件的生命周期, 坏处是写起来麻烦. function component的好处是可以使用高阶函数式的编程方式编写代码, 缺点是没有状态可以控制.所以一般需要状态初始化或者其他一些状态操控时, 以前可以用recompose, 使用HOC让组件带有状态, 但是后来这个库的作者加入了React团队, v16.8版本后, 我们应该使用Hooks来管理组件状态和生命周期.
recompose和hooks写法对比
使用recompose给组件设置状态及其他类似componentDidMount的功能时, 需要先定义好相应的状态和生命周期函数, 然后compose进组件:
1  | const { Component } = React;  | 
而如果使用Hooks那么改写起来方便一点.
1  | import React, {useState, useEffect} from 'react'  | 
- Title: React函数式组件的状态
 - Author: Kopei
 - Created at : 2019-04-18 00:00:00
 - Updated at : 2025-08-13 18:15:58
 - Link: https://kopei.github.io/2019/04/17/frontend-2019-04-18-React-function-component-state/
 - License: This work is licensed under CC BY-NC-SA 4.0.
 
        Comments