- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试使用 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/
我是一名优秀的程序员,十分优秀!