react hook useEffect 循优性和避免死循环

1、useEffect 介绍

useEffect 函数组件中执行副作用操作
相当于class组件生命周期的componentDidMount 和 componentDidUpdate
useEffect 有2个参数,
第1个为执行函数,
第2个参数存放变量并放在[],也就是函数的依赖,当第二个参数改变时,会重新执行第一个参数(函数)

2、useEffect 函数组件中执行顺序

组件reader 执行完后,执行useEffect,如果useEffect 函数执行过程中修改了useState的值就会重新render,从而导致的重复渲染

3、useEffect 正确使用

 useEffect(() => {
    
    
    // Update the document title using the browser API
    document.title = `You clicked ${
      
      count} times`;
  },[]);

4、 useEffect 函数导致循环的因素

那么我们看看第二个参数什么时候会导致重新渲染

1、如果没有第二个参数,那么就会无限循环执行逻辑处理函数

useEffect(() => {
    
    
    // Update the document title using the browser API
    document.title = `You clicked ${
      
      count} times`;
  });

2、如果第二个参数为引用类型时

1、数组

 useEffect(() => {
    
    
    // Update the document title using the browser API
    document.title = `You clicked ${
      
      count} times`;
  },[[]]);

比如如述代码,如果是这种情况,那么也会导致重新渲染,因为useEffect的依赖[ ]会和上一次的进行[]对比,
[]===[] //fasle
由于每次数组的声明,都会分配不同的存储空间,所以两次都为[],却都不相等,所以会导致重复渲染

猜你喜欢

转载自blog.csdn.net/weixin_45596949/article/details/125367769
今日推荐