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 ...
随机推荐
- 分享一个基于 netty 的 java 开源项目
1.简介 中微子代理(neutrino-proxy)是一个基于 netty 的.开源的 java 内网穿透项目.遵循 MIT 许可,因此您可以对它进行复制.修改.传播并用于任何个人或商业行为. 2.项 ...
- springboot执行流程
构造方法初始化,创建一个新的实例,这个应用程序的上下文要从指定的来源加载bean public SpringApplication(ResourceLoaderresourceLoader,Class ...
- ElasticSearch7.3学习(三十二)----logstash三大插件(input、filter、output)及其综合示例
1. Logstash输入插件 1.1 input介绍 logstash支持很多数据源,比如说file,http,jdbc,s3等等 图片上面只是一少部分.详情见网址:https://www.elas ...
- 关于我用python表白成功这件事【表白成功】
520,并非情人所属, 我们可以表白万物, 不管什么时候, 这都是一个特别的日子, 今天,我要表白所有, 心里有我的人! 在这个充满幸福的日子里, 我要把最美好的祝福, 送给心里有我的每一个人: 祝愿 ...
- NC14661 简单的数据结构
NC14661 简单的数据结构 题目 题目描述 栗酱有一天在网上冲浪的时候发现了一道很有意思的数据结构题. 该数据结构形如长条形. 一开始该容器为空,有以下七种操作. 1 a从前面插入元素a 2 从前 ...
- NC202498 货物种类
NC202498 货物种类 题目 题目描述 某电商平台有 \(n\) 个仓库,编号从 \(1\) 到 \(n\) . 当购进某种货物的时候,商家会把货物分散的放在编号相邻的几个仓库中. 我们暂时不考虑 ...
- 腾讯云数据库公有云市场稳居TOP 2!
7月4日,国际权威机构IDC发布的<2021年下半年中国关系型数据库软件市场跟踪报告>显示,腾讯云数据库在关系型数据库软件市场(公有云模式)中,位列第二. IDC报告显示,2021下半年中 ...
- 各种Git Bash乱码解决
乱码情景一: 当使用git log 出现乱码时,修改 %GIT_HOME%\etc\gitconfig 文件,加入如下内容: [gui] encoding = utf-8[i18n] commiten ...
- java.security.spec.InvalidKeySpecException: java.security.InvalidKeyException: IOException : DerInputStream.getLength(): lengthTag=111, too big.
RSA用私钥签名的时候发现报错,删除以下内容即可 -----BEGIN PRIVATE KEY----- -----END PRIVATE KEY----- import org.apache.com ...
- day09 集合排序_Collection接口与Collections工具类
集合的排序 java.util.Collections类 Collections是集合的工具类,里面定义了很多静态方法用于操作集合. Collections.sort(List list)方法 可以对 ...