未捕获的错误:只能在函数组件的主体内部调用钩子 [英] Uncaught Error: Hooks can only be called inside the body of a function component

查看:127
本文介绍了未捕获的错误:只能在函数组件的主体内部调用钩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的项目中使用新的 React 功能挂钩.我已经将 react 版本更新到 16.8.1 但是,它给出了错误

<块引用>

未捕获的错误: Hooks 只能在功能组件

package.json

"react": "^16.8.1","react-app-polyfill": "^0.2.0","react-dev-utils": "^7.0.1","react-dom": "^16.7.0",

index.js

function selectDoc() {const [selectedOrg, handleOrgChange] = useState("");返回 (<div className="select-info"><div className="select-showcase"><div style={{ marginRight: '20px' }}><div>使用搜索</div><选择项目={orgsList}selectedItem={selectedOrg}handleItemChange={handleOrgChange}/>

);}导出默认选择文档;

解决方案

您的代码似乎是正确的.但是,您尚未将 react-dom 更新为与 React 相同的版本,即 16.8.1,因此您会看到这个错误起初误导.reactreact-dom 都应该使用相同的版本才能正确使用 React 功能.

运行

yarn upgrade react-dom@16.8.1

react-dom 升级到 v16.8.1

如果你使用 npm 而不是 yarn,你可以运行

npm update --save react-dom@16.8.1

I am trying to use new react feature hooks in my project. I have updated react version to 16.8.1 however, it gives error

Uncaught Error: Hooks can only be called inside the body of a function component

package.json

"react": "^16.8.1",
"react-app-polyfill": "^0.2.0",
"react-dev-utils": "^7.0.1",
"react-dom": "^16.7.0",

index.js

function selectDoc() {
  const [selectedOrg, handleOrgChange] = useState("");
  return (
    <div className="select-info">
      <div className="select-showcase">
        <div style={{ marginRight: '20px' }}>
          <div>With Search</div>
          <Select           
            items={orgsList}
            selectedItem={selectedOrg}
            handleItemChange={handleOrgChange}
          />
        </div>
      </div>
    </div>
  );
}

export default selectDoc;

解决方案

Your code seems to be correct. However you haven't updated react-dom to the same version i.e 16.8.1 as React and hence you see this error which is a little misleading at first. Both react and react-dom should use the same version to be able to use React features correctly.

Run

yarn upgrade react-dom@16.8.1

to upgrade react-dom to v16.8.1

If you use npm and not yarn, you could run

npm update --save react-dom@16.8.1

这篇关于未捕获的错误:只能在函数组件的主体内部调用钩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆