react hooks 实现vue 中的 watch和 computed

React 中实现 watch

// useWatch.ts
import { useEffect, useRef } from 'react'

type Callback<T> = (prev?: T) => void
interface Config {
  immdiate: Boolean
}

const useWatch = <T>(data: T, callback: Callback<T>, config: Config = { immdiate: false }) => {
  const prev = useRef<T>()
  const { immdiate } = config
  const inited = useRef(false)
  const stop = useRef(false)
  useEffect(() => {
    const execute = () => callback(prev.current)
    if (!stop.current) {
      if (!inited.current) {
        inited.current = true
        immdiate && execute()
      } else {
        execute()
      }
      prev.current = data
    }
  }, [data])

  return () => stop.current = true
}

export default useWatch

import { useState } from 'react'
import useWatch from '/@/hooks/web/useWatch'
function App() {
  const [num, setNum] = useState(1)
  useWatch(num, (pre) => console.log(pre, num), { immdiate: true })
  return (
    <div>
      <div style={{ color: '#fff' }}>{num}</div>
      <button onClick={() => setNum(num + 1)}>点我</button>
    </div>
  )
}

React 中实现 computed
Vue 中的 computed
只要 name 或者 food 改变, mag 会更新成相应的值

<h1>{{msg}}</h1>

computed: { msg() { return `我是${this.name},我爱吃${this.food}` } }

在 React 中需要通过 useMemo 这个 hook 来来实现 computed 的效果

import { useState, useMemo } from 'react'
function Demo() {
  const [name, setName] = useState('林三心')
  const [food, setFood] = useState('泡面')

  // 实现computed的功能
  const msg = useMemo(() => `我是${name},我爱吃${food}`, [name, food]) // 监听name和food这两个变量

  const handleClick = (type: number) => {
    if (type === 1) {
      setName('大菜鸟')
    } else if (type === 2) {
      setFood('牛肉丸')
    }
  }

  return (
    <div>
      <button onClick={() => handleClick(1)}>修改name</button>
      <button onClick={() => handleClick(2)}>修改food</button>
      <h1>{msg}</h1>
    </div>
  )
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值