【发布时间】:2021-02-07 18:36:09
【问题描述】:
我试图使用 Material UI 在 React 中创建一个响应式导航栏,但是当窗口大小减小到 900 像素以下时,此代码会崩溃,并给出错误 Error: Rendered less hooks than expected.这可能是由于意外提前返回语句造成的。 错误在 useEffect 挂钩中。但我就是不明白为什么这会给我一个错误。我猜这是因为违反了钩子规则。但是我已经尝试了所有方法,但仍然无法修复它。
import React,{useEffect,useState} from 'react'
import {AppBar ,Toolbar, Container ,makeStyles,Button, IconButton ,Drawer} from '@material-ui/core'
import MenuIcon from '@material-ui/icons/Menu'
const usestyles = makeStyles({
root:{
display:'flex',
justifyContent:'space-between' ,
maxWidth:'700px'
},
menubtn:{
fontFamily: "Work Sans, sans-serif",
fontWeight: 500,
paddingRight:'79px',
color: "white",
textAlign: "left",
},
menuicon:{
edge: "start",color: "inherit",paddingLeft:'0'
}
})
const menudata = [
{
label: "home",
href: "/",
},
{
label: "About",
href: "/about",
},
{
label: "Skill",
href: "/skills",
},
{
label: "Projects",
href: "/projects",
},
{
label: "Contact",
href: "/contact",
},
];
function Navbar() {
const [state, setState] = useState({mobileview:false,draweropen:false});
const {mobileview,draweropen} = state;
const {menuicon,root} =usestyles();
function getmenubuttons(){
const {menubtn} = usestyles();
return menudata.map(({label,href})=>{
return <Button className={menubtn}>{label}</Button>
})
}
function displaydesktop(){
return <Toolbar >
<Container maxWidth={false} className={root}>
{getmenubuttons()}
</Container>
</Toolbar>
}
function displaymobile(){
return <Toolbar>
<IconButton className={menuicon} >
<MenuIcon />
</IconButton>
</Toolbar>
}
useEffect(() => {
const setResponsiveness = () => {
return window.innerWidth < 900
? setState((state)=>({ ...state, mobileview: true }))
: setState((state)=>({ ...state, mobileview: false }));
};
setResponsiveness();
window.addEventListener("resize", () => setResponsiveness());
}, []);
return (
<div>
<AppBar> {mobileview? displaymobile() :displaydesktop() } </AppBar>
</div>
)
}
export default Navbar;
【问题讨论】:
标签: reactjs react-hooks use-effect