Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/474.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 功能组件仅在部署后渲染两次_Javascript_Reactjs_React Hooks_Gatsby - Fatal编程技术网

Javascript 功能组件仅在部署后渲染两次

Javascript 功能组件仅在部署后渲染两次,javascript,reactjs,react-hooks,gatsby,Javascript,Reactjs,React Hooks,Gatsby,我有一个基于窗口宽度渲染滑块的功能组件: const Works = (props) => { const size = useWindowWidth() const codeWorksArray = CodeWorksQuery() const mapWorksArray = MapWorksMetadata() const setSliderItems = (width) => { if (width > config.deviceWidths.m

我有一个基于窗口宽度渲染滑块的功能组件:

const Works = (props) => {
  const size = useWindowWidth()
  const codeWorksArray = CodeWorksQuery()
  const mapWorksArray = MapWorksMetadata()

  const setSliderItems = (width) => {
    if (width > config.deviceWidths.medium) {
      return 4
    } else if (width >= config.deviceWidths.small) {
      return 2
    } else {
      return 1
    }
  }
...

<Slider sliderElements={mapWorksSliderItems} slidesCount={setSliderItems(size.width)}/>
滑块计数
值作为道具传递给
滑块
,并计算组件内每个滑块项目的宽度。问题是,一旦部署,滑块只有一个元素(而不是桌面上的4个)。似乎只有在调整大小后才会更新

在localhost上,这很好。部署后(Netlify)此组件渲染两次,但在第二次渲染后,它保留第一次渲染的信息。
是什么导致localhost和部署后的外观不同?

似乎缺少添加事件侦听器。你使用SSR吗?我的代码中没有缺少它,但这里确实有-我忘了用
addEventListener
复制行。我还不知道《盖茨比》中的SSR是什么。
import { useState, useEffect } from "react"

const useWindowWidth = () => {
  const isWindowAvailable = typeof window !== "undefined"

  const getSize = () => {
    return {
      width: isWindowAvailable ? window.innerWidth : undefined,
      height: isWindowAvailable ? window.innerHeight : undefined
    };
  }

  const [windowSize, setWindowSize] = useState(getSize)

  useEffect(() => {
    if (!isWindowAvailable) {
      return false
    }

    const handleResize = () => {
      setWindowSize(getSize())
    }

    window.addEventListener("resize", handleResize)
    return () => window.removeEventListener("resize", handleResize)
  }, [])

  return windowSize
}

export default useWindowWidth