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:

  1. You might be breaking the Rules of Hooks.
  2. You might have mismatching versions of React and React DOM.
  3. 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)。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部