正文从这开始~

总览

当我们有条件地使用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. 浏览器代理user-agent

    两种方法: 法1:浏览器地址栏输入:about://version,然后复制用户代理: 如果法1不行,法2肯定可以. 法2:打开任意浏览器,输入任意网址,下面以火狐和百度网址为例来进行说明: 打开火狐 ...

  2. VTK 在WINDOWS上的安装使用

    参考:http://www.vtk.org/Wiki/VTK/Building/Windows#Step_5_-_Open_the_Visual_Studio_project

  3. WindowsServer评估版转为正式版并激活

    更新记录 本文迁移自Panda666原博客,原发布时间:2021年5月16日. 一般从官网下载的Windows Server版本都是评估试用版本.这时候想转为正式版本,就需要使用转换激活代码.请参照不 ...

  4. 一张图进阶 RocketMQ - 整体架构

    前 言 三此君看了好几本书,看了很多遍源码整理的 一张图进阶 RocketMQ 图片链接,关于 RocketMQ 你只需要记住这张图!如果你第一次看到这个系列,墙裂建议你打开链接.觉得不错的话,记得点 ...

  5. Ubuntu远程桌面助手(URDC)

    目前自动驾驶域控制器项目中使用了英伟达的Orin芯片+Ubuntu20.04系统.域控属于典型的Headless设备,开发调试时需要连接显示器(HDMI/DP).鼠标和键盘,或者使用NoMachine ...

  6. 怎么理解相互独立事件?真的是没有任何关系的事件吗?《考研概率论学习之我见》 -by zobol

    1.从条件概率的定义来看独立事件的定义 2.从古典概率的定义来看独立事件的定义 3.P(A|B)和P(A)的关系是什么? 4.由P(AB)=P(A)P(B)推出"独立" 5.从韦恩 ...

  7. 运行时应用自我保护(RASP):应用安全的自我修养

    应用程序已经成为网络黑客想要渗透到企业内部的绝佳目标. 因为他们知道如果能发现并利用应用程序的漏洞,他们就有超过三分之一的机会成功入侵. 更重要的是,发现应用程序漏洞的可能性也很大. Contrast ...

  8. 一文详解JackSon配置信息

    背景 1.1 问题 Spring Boot 在处理对象的序列化和反序列化时,默认使用框架自带的JackSon配置.使用框架默认的,通常会面临如下问题: Date返回日期格式(建议不使用Date,但老项 ...

  9. 使用c++爬取股市数据,获取最新行情

    最近自己动手写个小软件(界面原生态,还没来得及加样式哈).每天看看潜力股懒人做法,不介意推荐.资源有限,只能观察一下低价股,分析一下运动规律,什么时候拉升,惯性如何 主要功能:读取网络数据:保存本地数 ...

  10. Codeforces Round #792 (Div. 1 + Div. 2) A-E

    Codeforces Round #792 (Div. 1 + Div. 2) A-E A 题目 https://codeforces.com/contest/1684/problem/A 题解 思路 ...