[英]Why my check box isn't updated after click?
我正在尝试使用 React Hooks 来更新项目列表。 当用户单击复选框时,应用程序应呈现已选择为已购买的项目。
我可以记录handPurchase()
的事件并且状态是正确的,但是,我无法使函数呈现最新状态。
通过课堂,我可以做到:
const handlePurchase() {
// ...
this.setState(updatedGroceries);
}
this.state.groceries.map(//...render list
这是代码:
export default function CheckboxList() {
let initialGroceries = [
{
id: "one",
text: "Apple",
purchased: false
},
{
id: "two",
text: "Banana",
purchased: false
}
];
const [groceries, setGroceries] = useState(initialGroceries);
const handlePurchase = (id: string) => () => {
groceries.forEach((item) => {
if (item.id === id) {
item.purchased = true;
}
});
setGroceries(groceries);
}
return (
<List>
{groceries.map((item) => {
const labelId = `checkbox-list-label-${item.id}`;
return (
<ListItem key={item.id} role={undefined} dense button onClick={handlePurchase(item.id)}>
<ListItemIcon>
<Checkbox
checked={item.purchased}
inputProps={{ 'aria-labelledby': labelId }}
/>
</ListItemIcon>
<ListItemText id={labelId} primary={item.text} />
</ListItem>
);
})}
</List>
);
}
另外,如果我这样做:
const updatedGroceries = groceries.forEach((item) => {
if (item.id === id) {
item.purchased = true;
}
});
setGroceries(updatedGroceries);
我收到此错误:
“void”类型的参数不能分配给“SetStateAction<{id: string;”类型的参数。 文本:字符串; 购买:布尔值; }[]>'。 TS2345
问题是forEach
没有像您期望的那样返回任何内容。 我猜您想使用setGroceries
将所提供的id
等于当前元素的已purchased
属性更新为true
。 所以你需要返回一个数组,例如使用Array.prototype.map()
。 从文档:
map() 方法创建一个新数组,其中填充了对调用数组中的每个元素调用提供的函数的结果。
我想以下内容可以为您工作:
const updatedGroceries = groceries.map((item) => {
if (item.id === id) {
item.purchased = true;
}
return item;
});
setGroceries(updatedGroceries);
在你的代码被分配给updatedGroceries
的forEach
其结果undefined
,因为它不返回任何东西,发现在这里的文档。
我希望这有帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.