【react】慎用useLayoutEffect转而使用useEffect

由于useLayoutEffect钩子是在dom获得后、渲染组件前。因此,如果在useLayoutEffect中设置一些长耗时的,或者死循环之类的任务,会导致内存堆栈溢出。这时候需要转用useEffect

// 适配全局宽度拉动变化时,legend显示数量
  React.useEffect(() => {
    
    
    const onResize = debounce(() => {
    
    
      let totalWidth = 0;
      const els = itemWrapRef.current;
      const spaceEl = spaceWrapRef.current;
      const {
    
     length } = options;
      let maxNum: number = length;
      let _noFullOpts = [...options];
      let isShow = false;
      els.forEach((el: any, index: number) => {
    
    
        // 累计宽度是否大于容器宽度,为了计算最大容个数
        if (el?.offsetWidth && spaceEl?.clientWidth) {
    
    
          const flag = totalWidth + el?.offsetWidth > spaceEl?.clientWidth;
          // console.log('width===>', spaceEl.clientWidth, totalWidth, flag);
          if (!flag) {
    
    
            maxNum = index + 1;
            totalWidth += el?.offsetWidth;
            isShow = false;
          } else {
    
    
            isShow = true;
          }
          if (length > 1) {
    
    
            _noFullOpts = options.slice(0, maxNum);
          }
        }
      });
      setIsShowMore(isShow);
      setNoFullOpts([..._noFullOpts]);
    }, 50);
    onResize();
    window.addEventListener('resize', onResize);
    return () => {
    
    
      window.removeEventListener('resize', onResize);
    };
  }, [options]);

猜你喜欢

转载自blog.csdn.net/hzxOnlineOk/article/details/133039142
今日推荐