【问题标题】:Keep Component from Rerendering with Custom Hooks使用自定义 Hook 防止组件重新渲染
【发布时间】:2020-09-02 11:17:01
【问题描述】:

我有一个自定义钩子useWindowSize,它可以监听窗口大小的变化。一旦窗口大小低于某个阈值,Menu 中的某些文本就会消失。这是在另一个自定义钩子useSmallWindowWidth 中实现的,它接受useWindowSize 的返回值并检查它是否小于阈值。

然而,即使只有嵌套状态发生变化,当窗口大小发生变化时,我的组件也会不断地重新呈现。重新渲染菜单平均需要大约 50 毫秒,如果我想让其他组件也响应的话,这会加起来。

那么我怎样才能防止组件重新渲染呢?我尝试通过在函数中传递return prev.smallWindow === next.smallWindow; 来尝试React.memo,但它不起作用。

到目前为止我的尝试:

//this hook is taken from: https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react

function useWindowSize() {     
    const [size, setSize] = useState([0, 0]);
    useLayoutEffect(() => {
      function updateSize() {
        setSize([window.innerWidth, window.innerHeight]);
      }
      window.addEventListener('resize', updateSize);
      updateSize();
      return () => window.removeEventListener('resize', updateSize);
    }, []);
    return size;
  }

function useSmallWindowWidth() {
  const [width] = useWindowSize();
  const smallWindowBreakpoint = 1024;
  return width < smallWindowBreakpoint;
}

function Menu() {
  const smallWindow = useSmallWindowWidth();
  return (
    <div>
      <MenuItem>
        <InformationIcon/>
        {smallWindow && <span>Information</span>}
      </MenuItem>
      <MenuItem>
        <MenuIcon/>
        {smallWindow && <span>Menu</span>}
      </MenuItem>
    </div>
  );
}

【问题讨论】:

    标签: reactjs react-hooks react-memo


    【解决方案1】:

    您可以尝试将所有 JSX 包装在 useMemo 中

    function App() {
      return useMemo(() => {
        return (
          <div className="App">
            <h1>Hello CodeSandbox</h1>
            <h2>Start editing to see some magic happen!</h2>
          </div>
        );
      }, []);
    }
    

    在 useMemo 的第二个参数的数组中放入什么变量应该让你的 jsx 重新渲染。如果设置了一个空数组(如示例中),则 jsx 永远不会重新渲染。

    【讨论】:

    • 欣赏,好心的先生。我会在一分钟内接受你的回答
    • 你刚刚为我节省了 50 毫秒!
    猜你喜欢
    • 2021-02-14
    • 1970-01-01
    • 2020-03-17
    • 2021-01-07
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-12
    相关资源
    最近更新 更多