react 系列 -- useEffect 传递不同参数的不同执行规则

241 阅读1分钟

原文地址 useEffect 传递不同参数有哪些执行规则? - 程序员劝退师

useEffect() 第一个参数是函数;第二个参数可选,填的话填数组

render 是指:当数据有发生变化,render 就触发一次

1、不传第二个参数

默认的行为,每次 render 后都会执行,一般表单控制中使用

类似于类组件中的 componentDidMoount 以及 componentDidUpdate

useEffect(() => {
    console.log('useEffect with no dependency')
})

2、第二个参数:传有多个值的数组

传入第二个参数,会遍历该数组,比较每一个值,有一个不相等就执行

类似于类组件中的 componentDidUpdate

useEffect(() => {
    console.log('useEffect widh specify dependency')
}, [state, props])

3、第二个参数:传空数组

因为第二个参数是空数组,所以每次 render 后都不会再执行

类似于类组件中的 componentDidMount

useEffect(() => {
    console.log('useEffect with empty dependency')
}, [])

4、第一个参数:返回一个函数

返回时传递一个函数进行卸载,在组件卸载时候调用

类似于类组件中 componentWillUnmout

useEffect(() => {
   console.log('useEffect widh specify callback'); 
  return () => { 
    console.log('useEffect with specify callback'); 
  } 
})