[英]Call of hooks is inside of functional component give error Hooks can only be called inside of the body of a function component
[英]Hooks can only be called inside the body of a function component error
每当我尝试在我的应用程序中使用钩子时,我得到的Hooks can only be called inside the body of a function component
错误。 我正在使用标准的webpack4 / babel配置,带有preset-env
和preset-react
插件。 我的react / react-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列出的陷阱,没有运气。
还有什么我需要包括的吗?
来自TJ Crowder的Stack Snippet版本(有效):
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
为空。 这仍然表明我没有使用正确版本的React / DOM,即使yarn list
告诉我它们都是16.8.4吗?
EDIT2: console.log
-ing显示父级渲染函数中的计数
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,如下所述: 我的所有代码在由Webpack编译时运行两次
这意味着React被包含两次,导致错误。 可悲的是,我之前的所有检查都是针对不同版本的,而不是同一版本的2个实例!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.