语法
useEffect(callBack, option)
callBack
useEffect(() => {
// 每次渲染的操作
...
// 可返回一个函数, 每次渲染时做一些清除操作
return () => { // 操作 }
})
option
第二个参数可选,需传一个数组
const [value, setValue] = setState('');
const [value2, setValue2] = setState('');
// 每次渲染都调用
useEffect(() => {})
// value或者value2变化时才调用
useEffect(() => {}, [value, value2])
如果想执行只运行一次的 effect(仅在组件挂载和卸载时执行),可以传递一个空数组([]
)作为第二个参数。
useEffect(() => {
// mounted时操作
return () => {
// unmount时操作
}
}, [])
执行顺序演示
// 代码片段
const [value, setValue] = useState('');
const [otherValue, setOtherValue] = useState('');
useEffect(() => {
console.log('mounted');
return () => console.log('unmount');
}, [])
useEffect(() => {
console.log('update');
return () => console.log('clear');
})
useEffect(() => {
console.log('updateValue');
return () => console.log('clearValue');
}, [value])
// ---初次进入组件----------
// mounted
// update
// updateValue
// ---改变value----------
// clear
// clearValue
// update
// updateValue
// ---改变otherValue--------
// clear
// update
// 卸载组件
// unmount
// clear
// clearValue