只能在函数组件的主体内部调用挂钩

时间:2019-03-18 17:48:08

标签: javascript reactjs

每当我尝试在应用程序中使用钩子时,都会收到Hooks can only be called inside the body of a function component错误。我正在使用带有preset-envpreset-react插件的标准webpack4 / babel配置。我的react / redom-dom版本使用纱线分辨率固定到16.8.4,因此React / dom版本中应该没有不匹配的地方。

这是最基本的用法:

import React, { useState } from "react";

function MyComp() {
  const [hello] = useState(0);

  return <div>HELLO {hello}</div>;
}
export default MyComp;

我检查了https://reactjs.org/warnings/invalid-hook-call-warning.html列出的陷阱,没有运气。

还有什么需要补充的吗?

T.J。的堆栈片段版本人群(有效):

const { useState } = React;

function MyComp() {
  const [hello] = useState(0);

  return <div>HELLO {hello}</div>;
}

ReactDOM.render(
  <MyComp />,
  document.getElementById("root")
);
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

编辑:调试错误表明

function resolveDispatcher() {
  var dispatcher = ReactCurrentDispatcher.current;
  !(dispatcher !== null) ? invariant(false, 'Hooks can only be called inside the body of a function component. (/* omitted url due to warning */ )') : void 0;
  return dispatcher;
}
react.development

使得dispatcher为空。即使yarn list告诉我它们都在16.8.4,这是否仍表明我没有使用正确版本的React / DOM?

EDIT2:console.log-在父级的渲染函数中显示一个计数

let count = 0;
class App extends Component {
  render() {
    count++;
    console.log("counter", count++);

    return (
      <MyComp />
    );
  }
}

export default App;

实际上运行两次:

VM239 bundle.js:141088 counter 1
App.js:46 counter 1

非常有趣-我无法解释为什么会发生这种情况(在尝试此实验之前,我的应用运行得很好-但这表明可能存在两个相互竞争的过程

1 个答案:

答案 0 :(得分:4)

问题出在我的webpack配置上-我同时使用了HtmlWebpackPlugin,同时将输出包的script标签添加到我的index.html中,如此处所述:All my code runs twice when compiled by Webpack

这意味着React被包含两次,从而导致错误。可悲的是,我以前的所有检查都是针对不同版本的,而不是同一版本的2个实例!