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

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

问题描述

我在使用 useState 挂钩时收到此错误.我有它的基本形式,查看 react docs 以供参考,但我仍然收到此错误.我已经准备好迎接面掌时刻了...

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 年 12 月

react-hot-loader 的新版本现已发布,链接.Hooks 现在可以开箱即用了.感谢作者 theKashey.

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 热加载器
  • Webpack、Babel、ESLint Airbnb

首先,确保你安装了 react@nextreact-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 正在转换为类组件.有理由——成为能够在 HMR 上强制更新,只要没有更新"方法证监会.我正在寻找强制更新的其他方式(像这样.所以RHL 正在扼杀证监会.

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.

热替换渲染".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.

我将起草一份 PR,以缓解这两个问题.它会起作用,但是不是今天.

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-加载器维护者,您可以尝试 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 错误:只能在函数组件内部调用 Hooks的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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