首页 > 解决方案 > React - 如何过滤下拉列表中的项目

问题描述

第一次遇到这种情况,请多多包涵。

我正在编写一个 React Web 应用程序,它从本地 db.json 文件中提取数据并使用 Context API 将其存储在全局状态中。我在页面上显示了数据,并且我有一个下拉列表,其中也包含了该数据的类别名称。

当我从列表中选择一个下拉项目时,我希望它将数据列表过滤到该选定类别。

目前,当您选择下拉项目时,我收到以下错误:

“TypeError:无法读取未定义的属性 'toLowerCase'”。

这告诉我,我可能没有正确访问“类别”数据。

这是 JSON 的示例,我想访问“类别”:

{
    "machines": [{
            "category": "Skid Steer and Compact Track Loaders",
            // ^^^ I want to access this
            "product_details": [{
                    "id": 1,
                    "model": "226D3",
                    "power": "67.1",
                    "rated_operating_capacity": "1550",
                    "operating_weight": "5849",
                    "description": "Built for tough work, the Caterpillar® Skid Steer Loaders incorporate big iron features. These machines deliver Cat reliability, durability, and efficient operation, even in the toughest working conditions.",
                    "image": "https://s7d2.scene7.com/is/image/Caterpillar/CM20190910-c686b-0fdbf"
                ]
            }
        ]
    }
}

这是过滤下拉项目的代码:

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

const [categories, setCategories] = useState("");

// DROPDOWN - filter based on category
const filterCategory = (e, category) => {
    setCategories(e.target.value);
    return category.toLowerCase().indexOf(categories.toLowerCase()) !== -1;
    // ^^^ this is where it throws the error
  };

这是呈现列表的代码:

return (
    <>
      <div className="row">
        <div className="col-lg-3">
          {/* Dropdown */}
          <div className="options">
            {!isLoading ? (
              <>
                <select
                  value={categories}
                  onChange={filterCategory}
                  className="product-dropdown"
                  name="product-dropdown"
                >
                  {data.map((item) => (
                    <option value={item.category}>{item.category}</option>
                  ))}
                </select>
              </>
            ) : (
              <p>Loading...</p>
            )}
          </div>
        </div>
      </div>
      {/* List of machines */}
      {!isLoading ? (
        <MachineList
          filterProducts={filterProducts}
          filterCategory={filterCategory}
        />
      ) : (
        "Loading..."
      )}
    </>
  );

有没有办法我可以访问“类别”并使其成为当我从下拉列表中选择一个选项时,页面过滤并仅显示属于特定类别的那些项目?

标签: javascriptreactjs

解决方案


const [selectedCategory, setSelectedCategory] = useState('')
const filteredProducts = data.filter(machine => machine.category.toLowerCase() === selectedCategory.toLowerCase())

<-->

<select
   value={selectedCategory}
   onChange={(e) => setSelectedCategory(e.target.value}
   className="product-dropdown"
   name="product-dropdown"
 >

 <MachineList
      filterProducts={filteredProducts}
 />

推荐阅读