react 自动更新状态

import { useMemo, useState } from "react"

// eslint-disable-next-line @typescript-eslint/no-explicit-any
export const useProxy = >(state: T): T => {

  const [value, setValue] = useState()

  const createProxy = (target: T): T => {

    return new Proxy(target, {
      get: Reflect.get,
      set: (target, key: keyof T, value, reciver) => {
        target[key] = value
        setValue(createProxy(target))
        return Reflect.set(target, key, value, reciver)
      }
    })

  }

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const initVlaue = useMemo(() => createProxy(state), [state])

  return value ?? initVlaue
}

是时候放弃useState了,这么写React更丝滑 - 掘金

你可能感兴趣的:(react.js,javascript,前端)