React: FC(Hooks) 对比 Class Component

Hooks 优点

  • 比 HOC 更优雅的逻辑复用方式。HOC 可能会带来嵌套地狱,而 Hooks 可以让你在无需修改组件结构的情况下复用状态逻辑
  • 更加函数式。
  • Hooks 可以更方便的让相关代码写在一起(可阅读性,可维护性更高)。Class Component 则会让相关代码分布在不同的声明周期中,不方便后续的代码维护以及阅读
  • 没有 this 上下文的问题
  • 更方便的依赖执行(useEffect, useMemo)。class component 需要在shouldComponentUpdate, componentDidUpdate… 这些生命周期中各种判断

Hooks 不足

  • 没有统一的错误处理,现阶段没有与componentDidCatch等效的Hooks 。而 Class Component 中有 componentDidCatch 和 getDerivedStateFromError
  • 只能在最顶层使用 Hook,并且必须确保 Hook 在每一次渲染中都按照同样的顺序被调用
  • 存在闭包问题。看下面的代码:
const App = () => {
  const [count, setCount] = useState(0)
  const onClick = () => console.log(count)
  
  return (
    <button
      onClick={() => {
        setCount(pre => pre + 1);
        onClick()
      }}
    >
      count 加1, 并且打印 count
    </button>
  )
}

统一的报错处理 componentDidCatch

我有一个简单的组件,它充当我的 React 应用程序中的错误边界,并将任何错误传递给日志服务。

它看起来像这样:

export class CatchError extends React.PureComponent {
  state = {
    hasError: false
  }

  componentDidCatch(error, info) {
    this.props.log({ error, info })
    this.setState({ hasError: true })
  }

  render() {
    const child = typeof this.props.children === "function"
      ? this.props.children({ error: hasError })
      : children

    return React.cloneElement(child, { error: this.state.hasError })
  }
}

是否有等效于 componentDidCatch 的 React 钩子(Hook)?所以我可以让这个组件成为一个函数而不是一个类?

所以它可能看起来像这样:

export function CatchError({ children, log }) {
  const [hasError, setHasError] = useState(false)
  const caught = useDidCatch()

  useEffect(() => {
    const [error, info] = caught
    log({ error, info })
    setHasError(true)
  }, [caught])

  const child = typeof children === "function"
    ? children({ error: hasError })
    : children

  return React.cloneElement(child, { error: hasError })
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

织_网

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值