gpt4 book ai didi

javascript - 为什么我的复选框在点击后没有更新?

转载 作者:行者123 更新时间:2023-12-01 00:16:17 25 4
gpt4 key购买 nike

我正在尝试使用 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);

我收到此错误:

Argument of type 'void' is not assignable to parameter of type 'SetStateAction<{ id: string; text: string; purchased: boolean; }[]>'. TS2345

最佳答案

问题是forEach不会像您期望的那样返回任何内容。我猜您想用 setGroceries 进行更新purchased提供 id 的元素上的属性等于当前的 true 。因此,您需要返回一个数组,例如 Array.prototype.map() 。来自文档:

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

我想以下内容可能适合您:

const updatedGroceries = groceries.map((item) => {
if (item.id === id) {
item.purchased = true;
}

return item;
});

setGroceries(updatedGroceries);

在您的代码中,您分配给 updatedGroceries forEach结果是 undefined因为它没有返回任何内容,所以找到 here in the docs .

希望对您有所帮助!

关于javascript - 为什么我的复选框在点击后没有更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59741107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com