简体   繁体   English

在 useEffect 挂钩中使用 matchMedia 会导致无限渲染

[英]Using matchMedia in a useEffect hook is causing infinite renders

I am using window.matchMedia to detect the screen size.我正在使用window.matchMedia来检测屏幕尺寸。 I want reload the page when it goes to a small screen.我想在页面进入小屏幕时重新加载页面。 However, my code is causing infinite renders.但是,我的代码导致无限渲染。 How can I fix this?我怎样才能解决这个问题?

export default function App(props) {
  const small = useMedia("(max-width: 400px)");
  const large = useMedia("(min-width: 800px)");
  if(small) {
    window.location.reload();
  }
  return (
    <div className="Media">
      <h1>Media</h1>
      <p>Small? {small ? 'Yes' : 'No'}.</p>
      <p>Large? {large ? 'Yes' : 'No'}.</p>
    </div>
  );
}

function useMedia(query) {
   const [matches, setMatches] = useState(
     window.matchMedia(query).matches
   );
   useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }

    const listener = () => setMatches(media.matches);
    media.addListener(listener);

    return () => media.removeListener(listener);
   }, [query]);

   return matches; 
}

This Article walks you through the process of handling Media query changes and how all the pieces fit together, in addition, the author also gives some tips (React tips) of how to avoid performance hits and suggests a solution. 本文将引导您完成处理媒体查询更改的过程以及所有部分如何组合在一起,此外,作者还给出了一些如何避免性能损失的提示(React Tips)并提出了解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM