React实现Vue中的computed、watch、mounted()、beforeDestroy()功能

React实现Vue中的computed、watch、mounted()、beforeDestroy()功能

import { useEffect, useState, useMemo } from "react";

export function Test () {
  const [firstName, setFirstName] = useState('xia')
  const [lastName, setLastName] = useState('xin')

  // computed
  const fullName = useMemo(() => {
    return `${firstName} ${lastName}`
  }, [firstName, lastName])

  useEffect(() => {
    // mounted()
    console.log('componentDidMount')
    return () => {
      // beforeDestroy()
      console.log('componentWillUnmount')
    }
  }, [])

  // watch
  useEffect(() => {
    console.log('fullName changed')
  }, [firstName, lastName])


  const changeFirstName = () => {
    setFirstName(firstName + '1')
  }

  const changeLastName = () => {
    setLastName(lastName + '2')
  }

  return (
    <>
      <p>{fullName}</p>
      <button onClick={changeFirstName}>改变firstName</button>
      <button onClick={changeLastName}>改变lastName</button>
    </>
  )
}

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