正文从这开始~

总览

当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditionally"错误。为了解决该错误,将所有React钩子移到任何可能油返回值的条件之上。

这里有个例子用来展示错误是如何发生的。

import React, {useState} from 'react';

export default function App() {
const [count, setCount] = useState(0); if (count > 0) {
return <h1>Count is greater than 0</h1>;
} // ️ React Hook "useState" is called conditionally.
//React Hooks must be called in the exact same order
// in every component render. Did you accidentally call
// a React Hook after an early return?
const [message, setMessage] = useState(''); return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

上述代码片段的问题在于,我们使用的第二个useState钩子,位于可能有返回值的条件之后。

顶层调用

为了解决该问题,我们必须在最顶层调用React钩子

import React, {useState} from 'react';

export default function App() {
const [count, setCount] = useState(0); // ️ move hooks above condition that might return
const [message, setMessage] = useState(''); // ️ any conditions that might return must be below all hooks
if (count > 0) {
return <h1>Count is greater than 0</h1>;
} return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

我们把第二个useState钩子移到了可能返回值的条件之上。

这样就解决了这个错误,因为我们必须确保每次组件渲染时,React钩子都以相同的顺序被调用。

这意味着我们不允许在循环、条件或嵌套函数内使用钩子。

我们绝不应该有条件地调用钩子。

import React, {useState} from 'react';

export default function App() {
const [count, setCount] = useState(0); if (count === 0) {
// ️ React Hook "useState" is called conditionally.
// React Hooks must be called in the exact same order in every component render.
const [message, setMessage] = useState('');
} return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}

上面的代码片段导致了错误,因为我们有条件地调用第二个useState钩子。

这是不允许的,因为钩子的数量和钩子调用的顺序,在我们的函数组件的重新渲染中必须是相同的。

为了解决这个错误,我们必须把useState的调用移到顶层,而不是有条件地调用这个钩子。

就像文档中所说的:

  • 只在最顶层使用 Hook
  • 不要在循环,条件或嵌套函数中调用 Hook
  • 确保总是在你的 React 函数的最顶层以及任何 return 之前使用 Hook
  • 在 React 的函数组件中调用 Hook
  • 在自定义 Hook 中调用其他 Hook

React报错之React hook 'useState' is called conditionally的更多相关文章

  1. React报错之React hook 'useState' cannot be called in a class component

    正文从这开始~ 总览 当我们尝试在类组件中使用useState 钩子时,会产生"React hook 'useState' cannot be called in a class compo ...

  2. React报错之Invalid hook call

    正文从这开始~ 总览 导致"Invalid hook call. Hooks can only be called inside the body of a function compone ...

  3. React报错之react component changing uncontrolled input

    正文从这开始~ 总览 当input的值被初始化为undefined,但后来又变更为一个不同的值时,会产生"A component is changing an uncontrolled in ...

  4. React报错之React Hook useEffect has a missing dependency

    正文从这开始~ 总览 当useEffect钩子使用了一个我们没有包含在其依赖数组中的变量或函数时,会产生"React Hook useEffect has a missing depende ...

  5. React报错之React Hook 'useEffect' is called in function

    正文从这开始~ 总览 为了解决错误"React Hook 'useEffect' is called in function that is neither a React function ...

  6. react 报错的堆栈处理

    react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...

  7. git commit -m "XX"报错 pre -commit hook failed (add --no-verify to bypass)问题

    在同步本地文件到线上仓库的时候 报错 pre -commit hook failed (add --no-verify to bypass) 当你在终端输入git commit -m "xx ...

  8. React报错之Expected `onClick` listener to be a function

    正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...

  9. React报错 :browserHistory doesn't exist in react-router

    由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...

随机推荐

  1. 浅析Kubernetes架构之workqueue

    通用队列 在kubernetes中,使用go的channel无法满足kubernetes的应用场景,如延迟.限速等:在kubernetes中存在三种队列通用队列 common queue ,延迟队列 ...

  2. 使用nodejs的wxmnode模块,开发一个微信自动监控提醒功能,做个天气预报。

    这个模块是一个公众号的模块,名字叫"帮你看着". 原本这个公众号是做股票监控提醒的,我也没炒股.因为接口支持写入任何内容,所以可以有其他的用处.比如做成天气预报定时提醒. 我们去n ...

  3. 线上问题定位利器 jprofiler

    1.导出dump windows: jps -l   查看Java进行 jmap -dump:format=b,file=webapi.hprof 20840 查看进程,根据进程号导出hprof文件 ...

  4. 学了WEB缓冲投毒-挖SRC的时候咋利用

    学了WEB缓冲投毒-挖SRC的时候咋利用 昨天发了哥WEB缓存投毒的学习文章,但是除了理论和训练营并无实践,正巧翻到了一篇文章,感觉还有点关系,转的一个国外的老哥的文章. 微信公众号:小惜渗透,欢迎大 ...

  5. 你难道不知道Vue-cookie?

    install npm install vue-cookies --save main.js import VueCookies from 'vue-cookies'Vue.use(VueCookie ...

  6. WPF 视频硬解码渲染播放(无空域)(支持4K、8K、高帧率视频)

    MediaWPF 基于 .NET 6 实现视频硬解码渲染Demo(无空域问题) 代码实现仅供学习参考 本项目视频渲染通过显卡进行视频解码,CPU几乎不参与工作,并且不存在令人烦躁的空域问题. 在播放摄 ...

  7. arcgis创建postgre企业级数据库

    什么是企业级地理数据库? 企业级地理数据库(ArcSD Enterprise,sde)是和 arcGIS 套件集成程度最高的地理数据库:创建时需要用到安装 arcGIS Server 时的 [ecp ...

  8. 端口被占用的问题解决 Web server failed to start. Port ×× was already in use

    出现此问题是端口被占用了,只需要关闭正在使用的端口就行 解决思路: 1.在服务器中更改port端口号,改为不冲突,没有被占用的端口. 2.找出被占用的端口,结束被占用的端口 解决结束被占用的端口的方法 ...

  9. Overfitting & Train Set & Test Set

    假设数据集是独立同分布的,可以将数据集划分为不同的比例:Train Set and Test Set. 同时在Train Set and Test Set上做精度测试,或者隔一段时间在Test Set ...

  10. BufferedImage类

    BufferedImage类(BufferedImage,是一个带缓冲区图像类,主要作用是将一副图片加载到内存中) BufferedImage类 是lmage的一个子类,BufferedImage 生 ...