首页 > 解决方案 > 我如何从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>
    ))
  );

标签: javascriptreactjs

解决方案


好吧,它应该看起来像这样:

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);
  }
}

推荐阅读