Skip to content

class 组件存在哪些问题

认识 React Hooks

  • 回顾 React 函数组件
  • state Hook
  • Effect Hook

React 函数组件

  • 没有组件实例
  • 没有生命周期
  • 没有 state 和 setState,只能接收 props
js
// class 组件
class ListDemo extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    return (
      <ul>
        {this.state.list.map((item, index) => {
          return (
            <li key={item.id}>
              index {index}; title {item.title}
            </li>
          );
        })}
      </ul>
    );
  }
}

// 函数组件
function List(props) {
  return (
    <ul>
      {props.list.map((item, index) => {
        return (
          <li key={item.id}>
            index {index}; title {item.title}
          </li>
        );
      })}
    </ul>
  );
}

class 组件存在哪些问题

  • 大型组件很难拆分和重构,很难测试(即 class 不易拆分)
  • 相同业务逻辑,分散到各个方法中,逻辑混乱
  • 复用逻辑变的复杂,如 Mixins、HOC、Render Prop

React 组件更易用函数表达

  • React 提倡函数式编程,view=fn(props)
  • 函数更灵活,更易拆分,更易测试
  • 但函数组件太简单,需要增加能力 - Hooks

基于 MIT 许可发布