React 中实现 computed

2,476 阅读1分钟

Vue 中的 computed

只要 name 或者 food 改变, mag 会更新成相应的值

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

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

React中实现

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

import { useState, useMemo } from 'react'
function Demo() {
  const [name, setName] = useState('666')
  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>
  )
}