react-第二章-useEffect

71 阅读1分钟

useEffect

useEffect 是 副作用的函数。

useEffect 充当类组件生命周期:  componentDidMount``componentDidUpdate 和 componentWillUnmount 

什么叫副作用函数呢?

会改变外部状态 或依赖外部可变状态的函数。如localStorage,ajax等依赖外部的叫副作用函数

执行时机

1.页面初始化,首次加载一下接口之类的

  1. 依赖项发生变化也会立刻执行,依赖性可以支持多个。
  2. 清理副作用函数,也可以做防抖
import { useEffect, useState } from "react"
// 子组件
const Child = (props: { name: string }) => {
   useEffect(() => {
      let timer = setTimeout(() => {
         fetch(`http://localhost:5174/?name=${props.name}`)
      }, 1000)
      return () => {
         clearTimeout(timer)
      }
   }, [props.name])
   return <div>Child</div>
}
const App = () => {
   const [show, setShow] = useState(true)
   const [name, setName] = useState('')
   return (
      <div id='data'>
         <div>
            <h3>父组件</h3>
            <input value={name} onChange={e => setName(e.target.value)} />
            <button onClick={() => setShow(!show)}>显示/隐藏</button>
         </div>
         <hr />
         <h3>子组件</h3>
         {show && <Child name={name} />}
      </div>
   )
}

export default App