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>
  )
}
Logo

前往低代码交流专区

更多推荐