【问题标题】:React - how to display all products using dropdown?React - 如何使用下拉菜单显示所有产品?
【发布时间】:2021-02-07 02:44:04
【问题描述】:

第一次尝试这样做,请多多包涵。

我正在使用下拉菜单根据类别从本地 JSON 文件中过滤产品数据。当用户选择一个类别时,下面的代码会根据类别过滤和显示产品。但是,我想在用户选择类别之前显示所有加载的产品。目前它只显示一个空白页面,直到用户单击一个类别,然后它会过滤并显示产品。

这是过滤器代码:

// Load in global state
  const { data, isLoading } = useAPI();

  const [selectedCategory, setSelectedCategory] = useState("All");

  const filteredCategories = data.filter(
    (machine) =>
      machine.category.toLowerCase() === selectedCategory.toLowerCase()
  );

JSON 是 here。

下拉代码:

<div className="options">
   {!isLoading ? (
   <>
   <select
      value={selectedCategory}
      onChange={(e) =>
      setSelectedCategory(e.target.value)}
      className="product-dropdown"
      name="product-dropdown"
      >
      <option value="">All</option>
      {data.map((item) => (
      <option value={item.category}>{item.category}</option>
      ))}
   </select>
   </>
   ) : (
   <p>Loading...</p>
   )}
</div>

最后是渲染产品的代码:

export default function MachineList({ filteredCategories, filteredSearch }) {
  return (
    <>
      {filteredCategories.map((item) => (
        <ul>
          {/* Filter and map through the second level of API */}
          <div className="row">
            {item.product_details.filter(filteredSearch).map((subItem) => (
              <MachineCard
                image={subItem.image}
                title={subItem.model}
                weight={subItem.operating_weight}
                power={subItem.power}
              />
            ))}
          </div>
        </ul>
      ))}
    </>
  );
}

知道如何在加载时显示所有产品吗?

【问题讨论】:

    标签: javascript json reactjs


    【解决方案1】:

    问题是您根据来自db.json 的产品类别是否等于selectedCategory 状态toLowerCase 进行过滤。

    这是一个问题的原因是因为它没有说明'All' 不是您数据中的一个类别这一事实。当selectedCategory 等于'All' 时,filter 调用将始终过滤掉您的所有数据。

    您希望'All' 表示:不要过滤数据。

    您可以通过将过滤器逻辑更改为以下内容来实现此目的:

    let filteredCategories = data;
    if (selectedCategory !== "All") {
      filteredCategories = data.filter(
        (machine) =>
          machine.category.toLowerCase() === selectedCategory.toLowerCase()
      );
    }
    

    也在您的选择中:

    <select
      value={selectedCategory}
      onChange={(e) => setSelectedCategory(e.target.value)}
      className="product-dropdown"
      name="product-dropdown"
    >
      <option value="">All</option>
      {data.map((item) => (
        <option value={item.category}>{item.category}</option>
      ))}
    </select>
    

    改变:

    <option value="">All</option>
    

    到:

    <option value="All">All</option>
    

    由于您将e.target.value 传递给setSelectedCategory,如果您选择'All' 以外的选项并在之后选择'All' 选项,则会导致您的selectedCategory 状态设置为空字符串。上述过滤器逻辑中的if 语句没有考虑到这一点。所以将选项value 属性更改为'All' 或在if 语句中添加一个额外的条件。我推荐前者。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 2018-08-16
      • 1970-01-01
      相关资源
      最近更新 更多