EffectHook可以让你在函数组件中进行副作用操作。这里提到了副作用。什么是副作用?除了状态相关的逻辑,比如网络请求,监听事件,查找dom。可以说,在使用useState或useEffect等hook之后,组件每次渲染时,都会生成本次渲染的state、function、effects的副本,与上次或后续render的内容保持一致。没关系。对于类组件,状态是一种引用形式。这导致两者之间存在一些差异。只要是副作用,都可以使用useEffect()引入。它的常见用途如下。获取数据(datafetching)事件监听或订阅(settingsetupasubscription)改变DOM(changingtheDOM)输出日志记录(logging)副作用随着组件加载而发生,所以当组件被卸载时,这些副作用可能需要清理干净。useEffect()允许返回一个函数,该函数在卸载组件时执行以清除副作用。如果您不需要清除副作用,则useEffect()不必返回任何内容。使用useEffect()时有一个注意事项。如果有多个副作用,应该调用多个useEffect(),而不是合并写在一起。一、参数规则1、可选2、数组类型3、取值为state或props2、参数和返回不同1、每次render后默认不传参的行为,一般用在表单控件中。类似于类组件中的componentDidMoount和componentDidUpdate。useEffect(()=>{console.log('useEffectwithnodependency')})2.第二个参数传了一个空数组,每次render后数组的值都没有变化,所以不会执行。类似于类组件中的componentDidMount。useEffect(()=>{console.log('useEffectwithemptydependency')},[])3.一个或多个值数组传递给第二个参数,并且只有一个值。如果值有变化,就会执行传入第二个参数,2个值的数组,比较每个值,不相等则执行;类似于类组件中的componentDidUpdate;useEffect(()=>{console.log('useEffectwidhspecifydependency')},[state,props])4、返回函数时,返回时传入一个函数unmount,组件卸载时调用;类似于类值中的componentWillUnmout。useEffect(()=>{console.log('useEffectwidhspecifycallback'); return()=>{ console.log('useEffectwithspecifycallback'); }})if如果你熟悉React类的生命周期功能,你可以将useEffectHook认为是三个功能的组合:componentDidMount、componentDidUpdate和componentWillUnmount。类示例扩展React.Component{constructor(props){super(props);this.state={count:0};}componentDidMount(){document.title=`你点击了${this.state.count}次`;}componentDidUpdate(){document.title=`你点击了${this.state.count}次`;}render(){return(
你点击了{this.state.count}次
你点击了{count}次