You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

关键修复点说明

  1. 添加类型定义:通过ProductItem和OrderDTO接口规范数据结构,避免any带来的类型隐患
  2. 重构筛选逻辑:在分类变更时直接用find定位对应分类,提取其产品列表存入状态,替代原无效的filter逻辑
  3. 绑定产品状态:产品下拉框遍历selectedProducts状态,每个产品单独生成<option>,解决颜色挤在一起的问题
  4. 修正拼写错误:修复selectedCateogary的拼写错误,确保状态更新正常
  5. 优化交互体验:给产品下拉框添加disabled属性,未选择分类时禁用,防止无效操作

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:32:12