【发布时间】:2020-03-30 08:30:25
【问题描述】:
我正在尝试从 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>
))
);
【问题讨论】:
-
我认为你应该怎么做是:i。 handleCheckboxChange(item.id) ii.在 handleCheckboxChange 里面,你的过滤器没问题,但它不知道你在点击哪个,因此,你需要像这样过滤: const handleCheckboxChange = (id) => { cart.filter(item => item.id !== id) ; // 这使它检查那些不在此 id 中的内容,但它并不完整,因为它仅适用于您单击的每 1 个项目,并且不考虑整个数组。你应该有一个状态来管理它,例如:this.state = { selected: [] };
-
在初始化 this.state 后,在 handleCheckboxChange 内部,如果 id 不在内部,则将 id 添加到
selected数组中,例如: const item = cart.find(item => item 。ID); this.setState({ selected: [...selected, ...[item ? item : null]] });在你确认之后,你可以进入 componentDidUpdate 或者如果你正在使用钩子,你可以在你的 useEffect 中进行。 Whenever the selected gets update, you dispatch with the new array -
@kyapwc 你能写出来回答吗,这样很难理解
-
嗯,它应该看起来像这样: this.state = { selected: cart.map(item => ({ ...item, checked: true })), }; handleCheckboxChange(id, checked) { this.setState({ selected: this.state.selected.map(item => { if (item.id === id) return { ...item, checked } return item; }) }) };
-
@kyapwc 请在回答中添加该内容
标签: javascript reactjs