gpt4 book ai didi

javascript - React useState 表现非常糟糕

转载 作者:行者123 更新时间:2023-12-02 19:05:53 26 4
gpt4 key购买 nike

我无法理解这段代码中的问题:

    export default function CustomPopup({wi,he,children}) {

//some code

const [popupSize,setPopupSize] = useState([`${wi}px`,`${he}px`])

const handlePopupSize = () =>{
let c = [];
(window.innerWidth < (wi/0.9)) ? c[0] = `90%` : c[0] = `${wi}px`;
(window.innerHeight < (he/0.8)) ? c[1] = `80%` : c[1] = `${he}px`;
if (c != popupSize) { setPopupSize(c) };
}

window.addEventListener("resize", handlePopupSize)

return (

<div className="popup--page--wrapper">
<div className="popup--box" style={{width: popupSize[0], height: popupSize[1]}}>
{ children }
</div>
</div>
)
}

当我调整页面大小时,页面严重滞后,甚至导致浏览器出现错误。代码似乎有问题,但我无法找出。提前致谢!

最佳答案

您需要在 useEffect Hook 中添加事件监听器。

import React, { useState, useEffect } from 'react'
.....
.....
useEffect(() => {

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

您当前的代码创建了一个 addEventListeners 循环,因为在每个渲染上都会创建一个监听器,并且设置状态会在每次调整大小时导致新的渲染。

关于javascript - React useState 表现非常糟糕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65060227/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com