首页 > 解决方案 > React Hooks:尝试从事件处理程序更改 UseState 变量时,它总是会重置

问题描述

我已经开始学习 React 并遇到了问题。我尝试建立一个事件处理程序来监听窗口调整大小并相应地更改状态,让我为不同的屏幕尺寸启用或禁用页面上的某些组件。

不幸的是,我遇到了重置状态变量的问题。我真的不知道为什么会这样。希望你们能在这里阻止我:)

这是我的代码:

import React, { useRef, useState, useEffect } from "react"

export default function Home() {

  const size = useRef(null)
  const [a, rerender] = useState(0)

  const mobileFrontpageSwitch = () => {
    if (window.innerWidth > 1350 && size.current !== "XL") {
      size.current = "XL"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    } else if (
      window.innerWidth <= 1350 &&
      window.innerWidth > 1024 &&
      size.current !== "L"
    ) {
      size.current = "L"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    } else if (
      window.innerWidth <= 1024 &&
      window.innerWidth > 550 &&
      size.current !== "M"
    ) {
      size.current = "M"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    } else if (window.innerWidth <= 550 && size.current !== "S") {
      size.current = "S"
      rerender(a + 1)
      console.log(a + " : " + size.current)
    }
  }
  useEffect(() => {
    mobileFrontpageSwitch()

    window.addEventListener("resize", mobileFrontpageSwitch)
    console.log("Added Resize Handler")

    return () => {
      // clean up the event handler when the component unmounts
      window.removeEventListener("resize", mobileFrontpageSwitch)
      console.log("Removed Resize Handler")
    }
  }, [])
  return(
    [...]
  )
}

断点是占位符。调整大小时的输出是这样的:

0 : XL
0 : L
0 : M
0 : L
0 : M
0 : S

当断点被击中时,它也不会重新渲染。

有谁知道为什么会这样?

非常感谢!

标签: javascriptreactjsreact-hookswindow-resize

解决方案


推荐阅读