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} />

最新文章

  1. 使用plsql创建表空间和用户
  2. CSS之表单元素
  3. java-commons-HttpClient超时设置setConnectionTimeout和setSoTimeout
  4. php和apache安装心得
  5. IPv6 tutorial 1 Get started now
  6. 【转】Android Recovery模式
  7. 给AVS添加描述(how to add a description to a video)
  8. NFinal 视图—用户控件
  9. 安装mongodb后启动报错libstdc++
  10. 处理 Vue 单页面应用 SEO 的另一种思路
  11. 在Javaava中stringBuilder的用法
  12. GJB150-2009军用装备实验室环境试验方法新版标准
  13. 5650 so easy
  14. Ubuntu15.04 + Matlab2014a + MatConvNet install and compile
  15. go http
  16. JDK1.8 LongAdder 空间换时间: 比AtomicLong还高效的无锁实现
  17. 中国移动物联网ONENET平台数据本地采集工具
  18. python 之路初(一):pycharm 安装 和 环境配置 和 中文乱码问题
  19. 设置 SSH 通过密钥登录
  20. UVA.1640.The Counting Problem / BZOJ.1833.[ZJOI2010]数字计数(数位DP)

热门文章

  1. 【数据结构与算法】单链表操作(C++)
  2. 【C学习笔记】一
  3. (火狐浏览器)前端以FormData类形成表单(含文件),通过ajax提交,PHP后端iconv()报“文件名含有非法字符”且POST中的‘Ttitle’丢失
  4. Go语言【项目】 websocket消息服务
  5. CSP2019-S游记
  6. Windows下使用Nexus搭建Maven私服
  7. C# GDI graphics.DrawImage 的参数问题
  8. IDEA连接MySQL数据库报错08001
  9. typing类型注解库
  10. Django---简易图书管理系统(B/S架构)