You are probably here because you got the following error message:
Hooks can only be called inside the body of a function component.
There are three common reasons you might be seeing it:
- You might be breaking the Rules of Hooks.
- You might have mismatching versions of React and React DOM.
- You might have more than one copy of React in the same app.
原因
多数情况是你违反了hooks的使用规则。
如果违反这些规则,可能会看到此错误。
function Bad({ cond }) {
if (cond) {
// Bad: inside a condition (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad() {
for (let i = 0; i < 10; i++) {
// Bad: inside a loop (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad({ cond }) {
if (cond) {
return;
}
// Bad: after a conditional return (to fix,
//move it before the return!)
const theme = useContext(ThemeContext);
// ...
}
function Bad() {
function handleClick() {
// Bad: inside an event handler (to fix, move it outside!)
const theme = useContext(ThemeContext);
}
// ...
}
function Bad() {
const style = useMemo(() => {
// Bad: inside useMemo (to fix, move it outside!)
const theme = useContext(ThemeContext);
return createStyle(theme);
});
// ...
}
class Bad extends React.Component {
render() {
// Bad: inside a class component (to fix,
//write a function component instead of a class!)
useEffect(() => {})
// ...
}
}
还有一种情况比较少见,
React 和 React DOM 版本不匹配
比如你可能正在使用尚不支持 Hooks的版本react-dom(< 16.8.0) 或(< 0.59)。
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » Reacr报错:Hooks can only be called inside the body of a function component.
发表评论 取消回复