reactjs - 使用自定义 Hook 防止组件重新渲染
问题描述
我有一个自定义挂钩useWindowSize
,可以监听窗口大小的变化。一旦窗口大小低于某个阈值,一些文本应该会在Menu
. 这是在另一个自定义钩子useSmallWindowWidth
中实现的,该钩子接受返回的值useWindowSize
并检查它是否小于阈值。
然而,即使只有嵌套状态发生变化,当窗口大小发生变化时,我的组件也会不断地重新呈现。重新渲染菜单平均需要大约 50 毫秒,如果我想让其他组件也响应的话,这会加起来。
那么我怎样才能防止组件重新渲染呢?我尝试React.memo
通过return prev.smallWindow === next.smallWindow;
在函数内部传递,但它没有用。
到目前为止我的尝试:
//this hook is taken from: https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react
function useWindowSize() {
const [size, setSize] = useState([0, 0]);
useLayoutEffect(() => {
function updateSize() {
setSize([window.innerWidth, window.innerHeight]);
}
window.addEventListener('resize', updateSize);
updateSize();
return () => window.removeEventListener('resize', updateSize);
}, []);
return size;
}
function useSmallWindowWidth() {
const [width] = useWindowSize();
const smallWindowBreakpoint = 1024;
return width < smallWindowBreakpoint;
}
function Menu() {
const smallWindow = useSmallWindowWidth();
return (
<div>
<MenuItem>
<InformationIcon/>
{smallWindow && <span>Information</span>}
</MenuItem>
<MenuItem>
<MenuIcon/>
{smallWindow && <span>Menu</span>}
</MenuItem>
</div>
);
}
解决方案
您可以尝试将所有 JSX 包装在 useMemo 中
function App() {
return useMemo(() => {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}, []);
}
将数组放入 useMemo 的第二个参数中,什么变量应该使您的 jsx 重新呈现。如果设置了一个空数组(如示例中),则 jsx 永远不会重新呈现。
推荐阅读
- authentication - Azure DevOps 是否支持 SSO(单点登录)?
- django - 如果我是该组的成员,如何查看其他组成员?
- kotlin - Kotlin:无法识别两个字符串相等
- java - 安卓软键盘输入法
- php - php正则表达式:如何匹配数字+字母+中文
- javascript - Javascript Input Datalist 不断添加选项
- pandas - 获取 pandas CSV 嗅探器方言信息
- android - 在前台有两个 Android 活动
- flutter - 在小部件树中检测到 Flutter Duplicate GlobalKeys
- r - R - 如何在不使用函数的情况下根据一组条件执行某些代码块?