![](/img/trans.png)
[英]Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component?
[英]Error Message: Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component
当我尝试运行我的应用程序时出现空白页,但没有任何内容被渲染。
挂机调用无效。 钩子只能在 function 组件的内部调用。 这可能由于以下原因之一而发生:
- 您可能有不匹配的 React 版本和渲染器(例如 React DOM)
- 你可能违反了 Hooks 规则
- 您可能在同一个应用程序中有多个 React 副本,请参阅https://reactjs.org/link/invalid-hook-call以获取有关如何调试和修复此问题的提示。
import React,{ useState} from 'react';
import styled from 'styled-components'
import MenuIcon from '@material-ui/icons/Menu';
import CloseIcon from '@material-ui/icons/Close';
function Header() {
const [burgerState,setBurgerState] = useState(false);
return (
<Container>
<a href='#'>
<img src='/images/logo.svg' alt=''/>
</a>
<MenuGroup>
<div>Model S</div>
<div>Model X</div>
<div>Model Y</div>
</MenuGroup>
<RightMenu>
<a href='#'>Shop</a>
<a href='#'>Tesla Account</a>
<MenuIconContainer onClick={ () => setBurgerState(true)} >
<MenuIcon/>
</MenuIconContainer>
</RightMenu>
<BurgerNav status={burgerState}>
<CloseContainer>
<Close onClick={ () => setBurgerState(false)} />
</CloseContainer>
<li><a href='#'>Model S</a></li>
<li><a href='#'>Model Y</a></li>
<li><a href='#'>Existing inventory</a></li>
<li><a href='#'>Used inventory</a></li>
<li><a href='#'>Trade-in</a></li>
<li><a href='#'>Cybertruck</a></li>
<li><a href='#'>Roadster</a></li>
<li><a href='#'>Semi</a></li>
<li><a href='#'>Charging</a></li>
</BurgerNav >
</Container>
)
}
export default Header;
const Container = styled.div`
display: flex;
min-height: 60px;
align-items: center;
justify-content: space-between;
padding: 0 20px;
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 10;
`;
const MenuGroup = styled.div`
display: flex;
text-transform: uppercase;
div {
font-weight: 600;
padding: 0 10px;
cursor: pointer;
}
@media(max-width: 760px) {
display: none;
}
`;
const RightMenu = styled.div`
display: flex;
a {
font-weight: 600;
text-transform: uppercase;
padding-right: 20px;
}
`;
const MenuIconContainer = styled.div`
display:flex;
align-iems:center;
cursor:pointer;
`;
const CloseContainer = styled.div`
display: flex;
justify-content: flex-end;
`
const Close = styled(CloseIcon)`
`;
const BurgerNav = styled.div`
position: fixed;
width: 300px;
background: white;
top: 0;
right: 0;
bottom: 0;
padding: 20px;
list-style: none;
transform: ${props => props.status ? 'translateX(0)' : 'translateX(100%)'};
transition: transform 0.2s ease-in;
li {
padding: 15px 0;
border-bottom: 1px solid rgba(0, 0, 0, .2);
a {
font-weight: 600;
}
}
`
您的组件没有无效的挂钩调用。 您的代码没问题,(除了第 27 行不相关的未定义“关闭”。您是说 MUI 中的“CloseIcon”吗?还有一个不相关的错字“MenuIconContainer 中的 align-iems。
检查其他组件,因为您在此处粘贴的代码没问题。 你在哪里调用无效的 Hook。 对于此错误,您可能只有 3 个原因会看到它:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.