每当我尝试在我的应用程序中使用 Hook 时,我都会收到 Hooks can only be called inside the body of a function component
错误。我使用的是标准的 webpack4/babel 配置,带有 preset-env
和 preset-react
插件。我的 react/react-dom 版本使用 yarn 分辨率固定到 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. 的 Stack Snippet 版本Crowder(有效):
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
为 null。这是否仍然表明我没有使用正确版本的 React/DOM,即使 yarn list
告诉我它们都在 16.8.4?
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
这非常有趣 - 我无法解释为什么会发生这种情况(在我尝试这个实验之前我的应用程序运行良好 - 但它表明可能有两个竞争进程发生冲突
最佳答案
问题出在我的 webpack 配置上——我同时使用了 HtmlWebpackPlugin,同时将输出包的脚本标签添加到我的 index.html,如下所述:All my code runs twice when compiled by Webpack
这意味着 React 被包含了两次,导致了错误。遗憾的是,我之前的所有检查都是针对不同版本的,而不是同一版本的 2 个实例!
关于javascript - Hooks can only be called inside of a function component 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55227271/