javascript - 我如何从reactjs中的可用项目列表中过滤选中的项目
问题描述
我正在尝试从 reactjs 中的给定列表中过滤项目列表,并且我必须将过滤后的列表传递给 redux 存储,以便我可以使其在其他组件中可用。我的清单看起来像这样。
这是我的代码,我不确定天气是否正确
const dispatch = useDispatch();
const handleCheckboxChange = (event) => {
if (event.target.checked === true) {
const filterd = cart.filter(c => c.checked);
console.log('filterd', filterd);
dispatch(checkItems(cart))
} else {
dispatch(uncheckItems(cart))
}
}
return (
cart.map(item => (
<Grid
style={{ borderBottom: "1px solid #d2d2d2" }}
container
className="margin15"
>
<Grid container spacing={16} justify="center" className="cart">
<Grid container justify="flex-end" item xs={1}>
<Checkbox
onChange={handleCheckboxChange}
style={{ padding: "0px" }}
/>
</Grid>
<Grid className="image" item xs={6}>
<img src={item.image._links.mainImage.href}></img>
</Grid>
<Grid item xs={4} container justify="space-around">
<CartItemDetails cart={item} />
</Grid>
</Grid>
</Grid>
))
);
解决方案
好吧,它应该看起来像这样:
this.state = {
selected: cart.map(item => ({ ...item, checked: true }))
};
const handleCheckboxChange = (id, checked) => {
this.setState({
selected: this.state.selected.map(item => {
if (item.id === id) return { ...item, checked }
return item;
})
})
};
componentDidUpdate(prevProps, prevState) {
if (prevState.selected !== this.state.selected) {
dispatch(this.state.selected);
}
}
推荐阅读
- powershell - PowerShell - 列出所有文件夹、子文件夹和每个包含的文件(递归)但以格式化方式(树视图)
- angular - 我收到来自未知元素的错误
- r - 在R中固定拉长的图形彼此相邻
- python - Discord.py 输出时没有反应表情符号
- docker - Jenkins 管道无法在 Jenkins 节点上运行远程脚本
- postgresql - 没有显式类型转换的 pg_restore 上不提供几何等式运算符
- python - How to cast values to custom type in SQLAlchemy with Postgres
- passport.js - 在使用 passport-github 时,尽管 user:email 范围,但 profile.emails 为空
- oracle - PLSQL:在条件和更新不起作用的地方插入触发器之前
- azure - How can I get the system key for Azure Function with custom domain for binding event grid trigger?