正文从这开始~

总览

当我们有条件地调用一个钩子或在所有钩子运行之前提前返回时,会产生"Rendered more hooks than during the previous render"错误。为了解决该错误,将所有的钩子移到函数组件的顶层,以及不要在条件中使用钩子。

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

// App.js

import {useEffect, useState} from 'react';

export default function App() {
const [counter, setCounter] = useState(0); // ️ Error: Rendered more hooks than during the previous render.
if (counter > 0) {
// ️ calling React hook conditionally
useEffect(() => {
console.log('hello world');
});
} return (
<div>
<button onClick={() => setCounter(counter + 1)}>toggle loading</button>
<h1>Hello world</h1>
</div>
);
}

代码的问题在于,我们有条件地调用了useEffect钩子。

顶层调用

为了解决该错误,我们必须将条件移到钩子内部。因为React钩子只能在顶层调用。

import {useEffect, useState} from 'react';

export default function App() {
const [counter, setCounter] = useState(0); // hook is called at top level (not conditionally)
useEffect(() => {
if (counter > 0) {
console.log('hello world');
}
}); return (
<div>
<button onClick={() => setCounter(counter + 1)}>toggle loading</button>
<h1>Hello world</h1>
</div>
);
}

我们将if语句移动到了useEffect钩子内部。

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

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

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

import {useState} from 'react';

export default function App() {
const [counter, setCounter] = useState(0); // ️ this returns before second hook runs if condition is met
if (counter > 0) {
return <h2>Returning early</h2>;
} // ️ Error because hook is called conditionally
const [color, setColor] = useState('salmon'); return (
<div>
<button onClick={() => setCounter(counter + 1)}>toggle loading</button>
<h1>Hello world</h1>
</div>
);
}

问题在于,第二个useState钩子只有在上面的条件没有满足时才会被调用。

条件之上

为了解决这个错误,把所有的钩子移到组件的顶层,在任何可能返回值的条件之上。

import {useState} from 'react';

export default function App() {
const [counter, setCounter] = useState(0); const [color, setColor] = useState('salmon'); // ️ condition that may return early must be below all hooks
if (counter > 0) {
return <h2>Returning early</h2>;
} return (
<div>
<button onClick={() => setCounter(counter + 1)}>toggle loading</button>
<h1>Hello world</h1>
</div>
);
}

我们把第二个useState钩子移动到有可能返回一个值的if条件上面。

这是很有帮助的,因为钩子现在在顶层,并且有可预测的行为,允许React在调用useStateuseEffect之间正确地保存状态。

就像文档中所说的那样:

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

这有助于React在多个useStateuseEffect调用之间保留钩子的状态。

React报错之Rendered more hooks than during the previous render的更多相关文章

  1. react 报错的堆栈处理

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

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

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

  3. react报错 TypeError: Cannot read property 'setState' of undefined

    代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...

  4. React报错之Cannot find name

    正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...

  5. React报错之Cannot find namespace context

    正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...

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

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

  7. React报错:Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix,

    今天在开发时报了以下错误,记录一下 我们不能在组件销毁后设置state,防止出现内存泄漏的情况 出现原因直接告诉你了,组件都被销毁了,还设置个锤子的state啊 解决方案: 利用生命周期钩子函数:co ...

  8. react报错this.setState is not a function

    当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...

  9. React报错之React hook 'useState' is called conditionally

    正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...

随机推荐

  1. 有关安装pycocotools的办法

    1,首先需要安装Visual C++ 2015构建工具,地址https://download.microsoft.com/download/5/f/7/5f7acaeb-8363-451f-9425- ...

  2. Idea创建文件夹自动合成一个

    在idea中创建文件夹时,它们总是自动合成一个,如下图: 文件夹自动折叠真的很影响效率,可能会引发一些不经意的失误 解决方法: 取消这个地方的勾选 这样就可以正常创建文件夹了

  3. 关于升级最新版本node.js你知道多少?

    1.先检查版本 node -v 2.清除缓存 npm cache clean -f 3.全局安装管理node.js版本工具 npm install -g n 4.确认安装最新版本 n stable 5 ...

  4. 一篇文章讲清楚MySQL的聚簇/联合/覆盖索引、回表、索引下推

    迎面走来了你的面试官,身穿格子衫,挺着啤酒肚,发际线严重后移的中年男子. 手拿泡着枸杞的保温杯,胳膊夹着MacBook,MacBook上还贴着公司标语:"加班使我快乐". 面试官: ...

  5. 自定义nginx的日志格式存储到Filebeat和Logstash

    vim /etc/nginx/nginx.conf log_format main '$remote_addr - $remote_user [$time_local] ' '"$reque ...

  6. 零基础学Java(6)控制流程

    控制流程 与任何程序设计语言一样,Java使用条件语句和循环结构确定控制流程. 块作用域 我们首先要了解块(block)的概念. 块是指由若干条Java语句组成的语句,并用一对大括号括起来.块确定了变 ...

  7. 什么是好的 API 设计?【eolink翻译】

    对于试图完善其 API 策略的团队来说,良好的 API 设计是一个经常出现的话题. API 设计的重要性相信不需要赘述,精心设计的 API 的好处包括:更好开发人员体验.更快的文档编制以及更高的 AP ...

  8. WSL2安装Ubuntu20.04

    前言:听说WSL2需要Window版本在1904以上(我的window版本是1909,所以未能验证真实性) 启用WSL 控制面板 → 程序 → 程序和功能 → 启用或关闭Windows功能 勾选 适用 ...

  9. python 文件操作(读写等)

    简介 在实际开发中我们需要对文件做一些操作,例如读写文件.在文件中新添内容等,通常情况下,我们会使用open函数进行相关文件的操作,下面将介绍一下关于open读写的相关内容. open()方法 ope ...

  10. Windows快捷安装应用方法(此处以Virtualbox为例)

    1.执行已下载的virtualbox的安装exe文件,使用pywinauto模拟点击Windows安装的对应控件 1.1.启动exe文件 start *.exe 1.2.使用pywinauto(也适用 ...