TypeScript React联动下拉框功能异常问题求助
问题修复:TypeScript React联动下拉框
问题分析
当前代码存在三个核心问题:
products数组只保留了productName,丢失了关键的categoryName,导致分类筛选逻辑完全失效- 产品下拉框仍在遍历完整的
data数据源,没有使用选中分类对应的状态值,所以始终显示所有产品 - 直接将
productName数组渲染到<option>中,数组会被自动转为逗号分隔的字符串,导致所有颜色挤在同一个选项里
修正后的代码
import { useState } from 'react'; import { useQuery } from '@tanstack/react-query'; import InputLabel from '@mui/material/InputLabel'; // 定义TypeScript类型,替代any,提升代码安全性 interface ProductItem { productName: string; } interface OrderDTO { _id: { $oid: string }; categoryName: string; productName: ProductItem[]; productQuantity: number; ordUpdated: { $date: string }; isInStock: boolean; } export const DependentDropdown = () => { // 修正拼写错误:selectedCateogary -> selectedCategory const [selectedCategory, setSelectedCategory] = useState(''); const [selectedProducts, setSelectedProducts] = useState<ProductItem[]>([]); const { data } = useQuery<OrderDTO[]>({ queryKey: ["ordlist"], queryFn: () => fetch("http://localhost:8080/portal") .then((res) => res.json()) }); const handleCategoryChange = (categoryName: string) => { setSelectedCategory(categoryName); // 匹配选中分类对应的产品列表 const matchedCategory = data?.find(row => row.categoryName === categoryName); // 更新产品状态,无匹配时清空 setSelectedProducts(matchedCategory?.productName || []); }; return ( <div> <InputLabel id="demo-simple-select-label">Category</InputLabel> <select className='select' value={selectedCategory} onChange={(e) => handleCategoryChange(e.target.value)} > <option value="">Select Category</option> {data?.map((row) => ( <option key={row._id.$oid} value={row.categoryName}> {row.categoryName} </option> ))} </select> <InputLabel id="demo-simple-select-label">Product</InputLabel> <select className='select' disabled={!selectedCategory}> <option value="">Select Product</option> {selectedProducts.map((product, index) => ( <option key={index} value={product.productName}> {product.productName} </option> ))} </select> </div> ); };
关键修复点说明
- 添加类型定义:通过
ProductItem和OrderDTO接口规范数据结构,避免any带来的类型隐患 - 重构筛选逻辑:在分类变更时直接用
find定位对应分类,提取其产品列表存入状态,替代原无效的filter逻辑 - 绑定产品状态:产品下拉框遍历
selectedProducts状态,每个产品单独生成<option>,解决颜色挤在一起的问题 - 修正拼写错误:修复
selectedCateogary的拼写错误,确保状态更新正常 - 优化交互体验:给产品下拉框添加
disabled属性,未选择分类时禁用,防止无效操作
内容的提问来源于stack exchange,提问作者Tony
相关产品推荐
相关产品推荐

