reactjs - Too Many Re Renders React JS - useState
问题描述
I have a mapped list of items as radio buttons. I am toggling the checked state.
I get an error from setCheckedState({i: false});
causing too many re renders.
How would I go about fixing this?
// Import useState
import { useState } from 'react';
// Set your active and SetActive items
const [active, setActive] = useState({});
{Object.values(equipment).map((item, i) => {
// Defautl the item to non active
setActive({i:false});
return (
<IonItem key={item}>
<IonLabel>{item}</IonLabel>
<IonRadio mode="md" slot="start" value={item} checked={active.i} onClick={() => {
// Set the specific Item to active
setActive({i:!active.i});
}} />
</IonItem>
);
})}
解决方案
正如 Jayce444 指出的那样,setActive({i:false});
由于无限循环,在渲染中会给您带来麻烦。
顺便说一句,你打错电话了setActive
。调用setActive({i:!active.i})
将完全覆盖状态对象为单个键/值对。一个例子:
假设你从
active = {1: true, 2: false}
// then you call
setActive({2:!active.2}) // now active looks like {2:!false} = {2: true}
// then you call
setActive({1:!active.1}) // now active looks like {1:!undefined} = {1: true}
// in this case you just happen to be getting lucky because
// all <IonRadio ... checked={active.i} ../> (other than your current set i)
// are evaluating to checked={undefined} which is the same as unchecked
您缺少的是在更新特定密钥之前复制现有状态。因此,将它们放在一起是一个可能的解决方案(此处为CodeSandbox)
const [active, setActive] = useState({});
const [oneOnly, setOneOnly] = useState("");
return (
<div className="App">
<h3>If you want to have multiple selections</h3>
{Object.values(equipment).map((item, i) => (
<label>
<input
key={item+"multi"}
type="radio"
value={item+"multi"}
checked={active[item] || false}
onClick={e => {
setActive({ ...active, [item]: !active[item] });
}}
/>
{i}) {item}
<br />
</label>
))}
<h3>... Or just one</h3>
{Object.values(equipment).map((item, i) => (
<label>
<input
key={item + "single"}
type="radio"
value={item + "single"}
checked={oneOnly === item}
onClick={e => {
setOneOnly(item);
}}
/>
{i}) {item}
<br />
</label>
))}
</div>
)
推荐阅读
- c# - 我们如何从现有数据库创建上下文文件,仅包括用户在 C# 中“以编程方式”访问的那些表?
- snowflake-cloud-data-platform - 描述雪花对象需要哪些授权?
- python - 删除 pandas DataFrame 中的行
- php - 如果存在其他参数,则从自定义帖子类型重写 url 后找不到错误 404 页面
- linux - 我正在尝试遍历目录并对它们执行命令
- python - 具有流数据的数据帧中的数据拆分
- java - 创建自己的数据结构类还是使用现有的实现?
- git - 如何检查 git commit 来自cherry-pick,来自哪个?
- java - 处理在android工具栏中单击菜单项
- python - 使用python编程在csv文件中搜索两个日期和两次之间的记录