[React] Fix "React Error: Rendered fewer hooks than expected"
2024-09-02 19:43:50
In this lesson we'll see an interesting situation where we're actually calling a function component and getting a dreaded React error: "Rendered fewer hooks than expected." We'll learn why that is happening, how it can be avoided, and how our "workaround" fixes the problem and avoids potential bugs.
More info: Don't call a React function component
Basiclly React hooks need to assoicate to one React component:
function Counter() {
const [count, setCount] = React.useState(0)
const increment = () => setCount(c => c + 1)
return <button onClick={increment}>{count}</button>
}
function BadCounterList() {
const [items, setItems] = React.useState([])
const addItem = () => setItems(i => [...i, {id: i.length}])
return (
<div>
<button onClick={addItem}>Add Item</button>
<div>{items.map(Counter)}</div>
</div>
)
}
The way we create Counter components is:
items.map(Counter)
Which React doesn't consider it is a React component, The hooks inside Counter function will be associated to BadCounterList. AKA: React function component doesn't work well with hooks.
function GoodCounterList(params) {
const [items, setItems] = React.useState([])
const addItem = () => setItems(i => [...i, {id: i.length}])
return (
<div>
<button onClick={addItem}>Add Item</button>
<div>
{items.map(i => (
<Counter key={i.id} />
))}
</div>
</div>
)
}
Here we create React component by using:
<Counter key={i.id} />
最新文章
- 使用plsql创建表空间和用户
- CSS之表单元素
- java-commons-HttpClient超时设置setConnectionTimeout和setSoTimeout
- php和apache安装心得
- IPv6 tutorial 1 Get started now
- 【转】Android Recovery模式
- 给AVS添加描述(how to add a description to a video)
- NFinal 视图—用户控件
- 安装mongodb后启动报错libstdc++
- 处理 Vue 单页面应用 SEO 的另一种思路
- 在Javaava中stringBuilder的用法
- GJB150-2009军用装备实验室环境试验方法新版标准
- 5650 so easy
- Ubuntu15.04 + Matlab2014a + MatConvNet install and compile
- go http
- JDK1.8 LongAdder 空间换时间: 比AtomicLong还高效的无锁实现
- 中国移动物联网ONENET平台数据本地采集工具
- python 之路初(一):pycharm 安装 和 环境配置 和 中文乱码问题
- 设置 SSH 通过密钥登录
- UVA.1640.The Counting Problem / BZOJ.1833.[ZJOI2010]数字计数(数位DP)
热门文章
- 【数据结构与算法】单链表操作(C++)
- 【C学习笔记】一
- (火狐浏览器)前端以FormData类形成表单(含文件),通过ajax提交,PHP后端iconv()报“文件名含有非法字符”且POST中的‘Ttitle’丢失
- Go语言【项目】 websocket消息服务
- CSP2019-S游记
- Windows下使用Nexus搭建Maven私服
- C# GDI graphics.DrawImage 的参数问题
- IDEA连接MySQL数据库报错08001
- typing类型注解库
- Django---简易图书管理系统(B/S架构)