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

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

问题描述

使用 useState 挂钩时出现此错误。我有它的基本形式,查看反应文档以供参考,但我仍然得到这个错误。我已准备好面对掌心...

I am getting this error when using the useState hook. I have this in it's basic form, looking at the react docs for a reference, but am still getting this error. I'm ready for the face palm moment...

export function Header() {
  const [count, setCount] = useState(0)
  return <span>header</span>
}


推荐答案

更新时间:2018-Dec



新版本的 react-hot-loader 现在已经出局,链接。钩子现在正在开箱即用。感谢作者,Kashey。

Updated: 2018-Dec

New version of react-hot-loader is out now, link. Hooks is now working out of the box. Thank to the author, theKashey.

查看此样板 https://github.com/ReeganExE/react-hooks-boilerplate


  • React Hooks

  • React Hot Loader

  • Webpack,Babel,ESLint Airbnb

首先,请确保已安装 react @ next react-dom @ next

First, make sure you installed react@next and react-dom@next.

然后检查您是否正在使用 react-hot-loader 或不。

Then check for you are using react-hot-loader or not.

在我的情况下,禁用热装载机& HMR可以让它发挥作用。

In my case, disable hot loader & HMR could get it work.

参见 https://github.com/gaearon/react-hot-loader/issues/1088

引用:


是的。 RHL 100%与钩子不兼容。它背后只有几个
的原因:

Yes. RHL is 100% not compatible with hooks. There is just a few reasons behind it:

SFC正被转换为Class组件。有理由 -
能够在HMR上强制更新,只要
SFC上没有更新方法。我正在寻找强制更新的其他方式(就像这样。所以
RHL正在杀死SFC。

SFC are being converted to Class components. There is reason - to be able to forceUpdate on HMR, as long there is no "update" method on SFC. I am looking for other way of forcing the update (like this. So RHL is killing SFC.

hotReplacementRender。RHL正在尝试做React的工作并渲染
旧的和新的应用程序,合并它们。所以,很明显,现在已经打破了

"hotReplacementRender". RHL is trying to do React's job, and render the old and the new app, to merge them. So, obviously, that's broken now.

我要去起草公关,以缓解这两个问题。它会工作,但今天不是

I am going to draft a PR, to mitigate both problems. It will work, but not today.

有一个更合适的修复,这将起作用 - 冷API

There is a more proper fix, which would work - cold API

您可以为任何自定义类型禁用RHL。

You may disable RHL for any custom type.

import { cold } from 'react-hot-loader';

cold(MyComponent);

在组件源代码中搜索useState / useEffect,并冷它。

Search for "useState/useEffect" inside component source code, and "cold" it.

根据更新,您可以尝试 react-hot-loader @ next 并设置配置如下:

As per updated from react-hot-loader maintainer, you could try react-hot-loader@next and set the config as bellow:

import { setConfig } from 'react-hot-loader';

setConfig({
  // set this flag to support SFC if patch is not landed
  pureSFC: true
});

感谢@loganfromlogan的更新。

Thank to @loganfromlogan for the update.

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

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆