javascript - 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
当断点被击中时,它也不会重新渲染。
有谁知道为什么会这样?
非常感谢!
解决方案
推荐阅读
- java - 检查用户是否来自加利福尼亚
- java - 线程“主”java.lang.IllegalArgumentException 中的异常:在 META-INF/spring.factories 中找不到自动配置类
- c# - C# WPF 组合框 DISplayMemberPath 不显示
- java - 可以使用用户名密码流访问使用 EWS 的交换收件箱吗?
- pdf - 带有 TSA 时间戳的 PDF 签名
- javascript - Javascript - 在每个第 4 个元素之后将对象数组拆分为多个数组
- html-email - 电子邮件:图像和文本对齐问题
- android - 我应该在使用 MediaCodec 解码期间使用 ImageReader 来访问 Image
- java - 检索成员详细信息后添加成功响应
- r - 在数据集中按行选择顺序数据的函数