Reactjs 防止组件使用自定义挂钩重新招标
我有一个自定义钩子Reactjs 防止组件使用自定义挂钩重新招标,reactjs,react-hooks,react-memo,Reactjs,React Hooks,React Memo,我有一个自定义钩子useWindowsSize,用于监听窗口大小的更改。一旦窗口大小低于某个阈值,一些文本就会在菜单中消失。这是在另一个自定义钩子usesmollwindowwidth中实现的,该钩子接受useWindowsSize的返回值,并检查它是否小于阈值 但是,即使只有嵌套状态更改,当窗口大小更改时,我的组件也会不断重新加载。重新打开菜单平均需要50毫秒,如果我想让其他组件也能响应的话,那么这加起来就需要50毫秒 那么,我如何才能防止组件重新招标?我通过传递return prev.sma
useWindowsSize
,用于监听窗口大小的更改。一旦窗口大小低于某个阈值,一些文本就会在菜单中消失。这是在另一个自定义钩子usesmollwindowwidth
中实现的,该钩子接受useWindowsSize
的返回值,并检查它是否小于阈值
但是,即使只有嵌套状态更改,当窗口大小更改时,我的组件也会不断重新加载。重新打开菜单平均需要50毫秒,如果我想让其他组件也能响应的话,那么这加起来就需要50毫秒
那么,我如何才能防止组件重新招标?我通过传递return prev.smallWindow===next.smallWindow,尝试了React.memo
代码>在函数中,但它不起作用
我迄今为止的努力:
//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>
);
}
//此挂钩取自:https://stackoverflow.com/questions/19014250/rerender-view-on-browser-resize-with-react
函数useWindowsSize(){
const[size,setSize]=useState([0,0]);
useLayoutEffect(()=>{
函数updateSize(){
设置大小([window.innerWidth,window.innerHeight]);
}
addEventListener('resize',updateSize);
updateSize();
return()=>window.removeEventListener('resize',updateSize);
}, []);
返回大小;
}
函数useSallWindowWidth(){
const[width]=useWindowsSize();
常量smallWindowBreakpoint=1024;
返回宽度<小窗口断点;
}
功能菜单(){
const smallWindow=UseSallWindowWidth();
返回(
{smallWindow&&Information}
{smallWindow&&Menu}
);
}
您可以尝试将所有JSX包装在UseMoom中
function App() {
return useMemo(() => {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}, []);
}
函数应用程序(){
返回UseMoom(()=>{
返回(
你好,代码沙盒
开始编辑,看看神奇的发生!
);
}, []);
}
在useMemo的第二个参数的数组中放入应该使jsx重新启动的变量。如果设置了空数组(如示例中所示),jsx将永远不会重新运行。感谢您,先生。我马上就接受你的回答,你刚才救了我50毫秒!