[react] Use useLayoutEffect with caution and use useEffect instead

Because useLayoutEffectthe hook is after the dom is obtained and before the component is rendered. Therefore, if useLayoutEffectyou set some long-term or infinite loop tasks in it, it will cause the memory stack to overflow. This is when you need to switch 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]);

Guess you like

Origin blog.csdn.net/hzxOnlineOk/article/details/133039142