简体   繁体   中英

react gets stuck after i resize the browser window

I used react-simple-image-slider for image slider on my website, but after i resize the browser window the application gets stucked.

The main Aim is to make the react-simple-image-slider responsive.

The below is the code.

import './App.css';
import {useLayoutEffect, useState } from 'react';
import SimpleImageSlider from 'react-simple-image-slider';

function App() { 
  const [widthAndHeight, setwidthAndHeight] = useState([window.innerWidth, 600]);
  
  useLayoutEffect ( ()=>
  {
    function updateTheWidthAndHeight()
    {
      setwidthAndHeight([window.innerWidth, 600]);
      
    }
      window.addEventListener('resize', ()=>{
      updateTheWidthAndHeight();
    })
  })

  const images = [
    { url: "logos/ethiopia.png" },
    { url: "logos/favicon.ico" },
    { url: "logos/gear.png" },
    { url: "logos/gear.jpg" }
  ];


  return (
      <div>
            <SimpleImageSlider
                style={{ margin: '0 auto', marginTop: '0px'}}
                className="slider"
                width={widthAndHeight[0]}
                height={widthAndHeight[1]}
                slideDuration={1}
                loop={true}
                autoPlay={true}
                images={images}
                showBullets={false}
                showNavs={true}
            />
      </div>
  );
}

export default App;

You forgot a dependency list for useLayoutEffect so it's adding an event listener on every render. Add an empty list for one-time execution:

useLayoutEffect(() => {
  function updateTheWidthAndHeight() {
    setwidthAndHeight([window.innerWidth, 600]);
  }
  window.addEventListener("resize", () => {
    updateTheWidthAndHeight();
  });
}, []);

I suggest you use useEffect instead of useLayoutEffect .
Maybe it will cause blocking visual updates.

Ref: https://reactjs.org/docs/hooks-reference.html#uselayouteffect

Hope this might help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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