React报错之Rendered more hooks than during the previous render
正文从这开始~
总览
当我们有条件地调用一个钩子或在所有钩子运行之前提前返回时,会产生"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在调用
useState和useEffect之间正确地保存状态。
就像文档中所说的那样:
- 只从React函数组件或自定义钩子中调用Hook
- 只在最顶层使用 Hook
- 不要在循环,条件或嵌套函数中调用 Hook
- 确保总是在你的 React 函数的最顶层以及任何 return 之前使用 Hook
这有助于React在多个useState和useEffect调用之间保留钩子的状态。
React报错之Rendered more hooks than during the previous render的更多相关文章
- react 报错的堆栈处理
react报错 Warning: You cannot PUSH the same path using hash history 在Link上使用replace 原文地址https://reactt ...
- React报错 :browserHistory doesn't exist in react-router
由于版本问题,React中history不可用 import { hashHistory } from 'react-router' 首先应该导入react-router-dom包: import { ...
- react报错 TypeError: Cannot read property 'setState' of undefined
代码如下: class test extends Component { constructor(props) { super(props); this.state = { liked: false ...
- React报错之Cannot find name
正文从这开始~ .tsx扩展名 为了在React TypeScript中解决Cannot find name报错,我们需要在使用JSX文件时使用.tsx扩展名,在你的tsconfig.json文件中把 ...
- React报错之Cannot find namespace context
正文从这开始~ 总览 在React中,为了解决"Cannot find namespace context"错误,在你使用JSX的文件中使用.tsx扩展名,在你的tsconfig. ...
- React报错之Expected `onClick` listener to be a function
正文从这开始~ 总览 当我们为元素的onClick属性传递一个值,但是该值却不是函数时,会产生"Expected onClick listener to be a function" ...
- 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 ...
- react报错this.setState is not a function
当报错这个的时候就要看函数是否在行内绑定this,或者在constructor中绑定this. 我这里犯的错误的是虽然我在constructor中绑定了this,但是语法写的不正确. 错误示范: co ...
- React报错之React hook 'useState' is called conditionally
正文从这开始~ 总览 当我们有条件地使用useState钩子时,或者在一个可能有返回值的条件之后,会产生"React hook 'useState' is called conditiona ...
随机推荐
- Chrome自带功能实现网页截图
更新记录 本文迁移自Panda666原博客,原发布时间:2021年6月28日. 很简单,按下Ctrl+Shift+P,打开命令行窗口,如下图所示. 输入命令. Capture full size sc ...
- 2.NoSQL之Redis配置与优化
一.关系型数据库与非关系数据库 关系型数据库: 关系型数据库是一个结构化的数据库,创建在关系模型(二维表格模型)基础上,一般面向于记录. sQL语句(标准数据查询语言)就是一种基于关系型数据库的语言, ...
- vue 的常用事件
vue 的常用事件 事件处理 1.使用 v-on:xxx 或 @xxx 绑定事件,其中 xxx 是事件名: 2.事件的回调需要配置在 methods 对象中,最终会在 vm 上: 3.methods ...
- 12.1 Android Studio如何手动下载Gradle文件
实际操作过程中,可能由于各方面原因,导致Gradle无法下载,或者下载比较慢,这个时候,其实我们可以手动下载,或者找一个最近的版本,替换他. 确认要下载的版本 不论是用命令编译Android项目,还是 ...
- 未找到与名为“xxx”的控制器匹配的类型。
自己封装了一个BaseApiControllerr把他独立成一个项目出来在引用不行,而用默认自带的ApiControllerr可以. <Error> <Message> 未找到 ...
- HDFS、Yarn、Hive…MRS中使用Ranger实现权限管理全栈式实践
摘要:Ranger为组件提供基于PBAC的鉴权插件,供组件服务端运行,目前支持Ranger鉴权的组件有HDFS.Yarn.Hive.HBase.Kafka.Storm和Spark2x,后续会支持更多组 ...
- Codeforces Round #768 (Div. 2) D. Range and Partition // 思维 + 贪心 + 二分查找
The link to problem:Problem - D - Codeforces D. Range and Partition time limit per test: 2 second ...
- CF1612D X-Magic Pair
题意: 给一个数对 \((a,b)\) ,每次可以进行操作 \((a,b) \to (|a-b|,b)\) 或 \((a,b) \to (a,∣a−b∣)\),问最后能否令 \(a=x\) 或 \(b ...
- 使用codeblocks创建新项目
很多同学在学习C或C++版的数据结构的时候,自己写项目是一个不错的锻炼方法,而用codeblocks写项目的时候我们就会遇到很多问题了,比如说: 1.如何建立新项目. 2.如何建立头文件和主函数文件. ...
- 2521-Shiro系列-基本使用
在springboot中使用SHiro作为安全框架,非常简单,灵活性也比较高 在springboot中使用Shiro不用像官网教程那样,官网是将配置文件写在INI文件和XML配置中 springboo ...