Hooks 使用规则

Hooks 使用规则

命名规则

Hook 必须 useXxx 格式来命名。

PS:这种命名规则也很易读,简单粗暴

调用位置

Hook 或自定义 Hook ,只能在两个地方被调用

  • 组件内部
  • 其他 Hook 内部

组件外部,或一个普通函数中,不能调用 Hook

顺序一致

Hook 在每次渲染时都按照相同的顺序被调用。

  • Hook 必须是组件“第一层代码”
  • Hook 不可放在 if 等条件语句中 ( 或者前面有 return ,也算是条件 )
  • Hook 不可放在 for 等循环语句中

代码演示

闭包陷阱

异步函数中获取 state 时,可能不是最新的 state 值。

解决方案:替换为 useRef —— 但 ref 变化不会触发 rerender ,所以得结合 state 一起

代码参考 src/pages/ClosureTrap.tsx

import React, { FC, useState, useRef, useEffect } from 'react'

const Demo: FC = () => {
  const [count, setCount] = useState(0)
  const countRef = useRef(0)
  useEffect(() => {
    countRef.current = count
  }, [count])

  function add() {
    setCount(count + 1)
  }

  function alertFn() {
    setTimeout(() => {
      //   alert(count) // count 值类型
      alert(countRef.current) // ref 引用类型
    }, 3000)
  }

  return (
    <>
      <p>闭包陷阱</p>
      <div>
        <span>{count}</span>
        <button onClick={add}>add</button>
        <button onClick={alertFn}>alert</button>
      </div>
    </>
  )
}

export default Demo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员柚子

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

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

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

打赏作者

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

抵扣说明:

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

余额充值