根据一系列选定项过滤产品-React

时间:2020-10-12 22:22:37

标签: javascript reactjs

我在类似的页面上列出了一系列产品:

{products.map((product, i) => {
  return (
    <p>{product.name}</p>
  )
})}

我在页面上有一个组件,其中每个产品类别都有复选框。我正在尝试这样做,以便可以通过选中的任何复选框来过滤产品列表,它可以是一个或多个。

到目前为止,我已经掌握了全部代码:

  const [products, setProducts] = useState([]);
  useEffect(() => {
    fetch(state.source.api + "/cocart/v1/products")
      .then((response) => response.json())
      .then((data) => {
        setProducts(data);
      });
  }, []);

  // Adds each item selected into an array of "selected" items
  const newArr = state.theme.filters.categories.flatMap(category => category.data).filter(item => item.checked);

  const [filteredProducts, setfilteredProducts] = useState(null);

  var A = products.filter(e => e.categories.find(category => category.slug === "for-kids"));
  var B = products.filter(e => e.categories.find(category => category.slug === "for-me") && e.categories.find(category => category.slug === "soft"));

  function showA() {
    setfilteredProducts(A)
  }
  function showB() {
    setfilteredProducts(B)
  }

  return (
    <>
      <button onClick={() => showA()}>For Kids</button>
      <button onClick={() => showB()}>Me & Soft</button>

      {filteredProducts && filteredProducts.map((item, id) => {
        return (
          <p>{item.name}</p>
        )
      }}
    </>
  )

newArr返回选定的项目,如下所示:

enter image description here

现在,按钮就在那里进行初始测试。最终,处于弹出模式的复选框一旦被选中,则产品将基于所选的复选框自动更新。现在,第二个按钮只是一个视觉效果。如果我可以使该按钮显示结果,那么我可以从那里去。

我的问题是,我正在尝试设置函数showB,以便它将根据newArr中的项目-选中的复选框进行过滤。但是我无法弄清楚如何编写showB函数,以便它会按newArr中的项目进行过滤。

任何帮助将不胜感激!

更新:

products返回以下内容:

{
  "id": 23901,
  "name": "5000 Close Out",
  "price": "$219.00",
  "on_sale": true,
  "categories": [
    {
      "id": 217,
      "name": "For Guest Rooms",
      "slug": "for-guest-rooms"
    },
    {
      "id": 216,
      "name": "For Kids",
      "slug": "for-kids"
    },
    {
      "id": 221,
      "name": "Medium-Firm",
      "slug": "medium-firm"
    },
    {
      "id": 224,
      "name": "Pocketed Coil",
      "slug": "pocketed-coil"
    }
  ],
}

1 个答案:

答案 0 :(得分:0)

如我所见,这就是Product类的样子

class Category {
   ...
   slug?: string;
   ...
}
class Prodcut {
 categories?: Category[];
}

这是组件的伪实现

...
products?: Product[]; // you set the value of this from api call
filteredProducts?: Product[] = []; // the filtered products based on the selected category. you should use this variable in your template to render the produts and as when you get the products, set the value of filteredProducts = products
filters: string[] = []; // all the selected filters

filterB(): void {
    filteredProducts = this.products.filter(product => {
        var allow = false;
        for(const temp of product.categories){
            if(!allow){
               allow = this.filters.includes(temp.slug)
            }
        }
        return allow;
    });
}
...

filterB函数将filteredProducts的值设置为调用时的值