我是 Typescript React 的新手,我试图创建两个从属选择框来从 API 中获取数据,但遇到了一点困难。当我在类别中选择颜色时,我只希望在产品下拉菜单中选择颜色,但我也得到了所有其他产品,而且它在一个选项中水平显示所有颜色。这是我到目前为止尝试过的方法。
我的 MongoDB 结构
"_id": {
"$oid": "679a70442a02723a1ad65e5d"
},
"categoryName": "Colours",
"productName": [
{
"productName": "Red"
},
{
"productName": "Blue"
},
{
"productName": "Yellow"
},
{
"productName": "Green"
}
],
"productQuantity": 90,
"ordUpdated": {
"$date": "2025-01-29T18:15:32.969Z"
},
"isInStock": false,
"_class": "com.softoffice.portal.model.OrderDTO"
打字稿
export const DependentDropdown = () => {
const [selectedCateogary, setSelectedCategory] = useState('');
const [selectedProd, setSelectedProd] = useState([]);
const { data } = useQuery({
queryKey: ["ordlist"],
queryFn: () => fetch("http://localhost:8080/portal")
.then((res) => res.json())
})
const products = data?.map((row: any) => ({
productName: row.productName?.map((p: { productName: string; }) => p.productName)
}))
const handleChange = (id:string) => {
const pd = products.filter((c: any) => c.categoryName === id);
setSelectedProd(pd);
}
return (
<div>
<InputLabel id="demo-simple-select-label">Category</InputLabel>
<select className='select' onChange={(e) => handleChange(e.target.value)} >
<option>Select Category</option>
{data?.map((row: { categoryName: any }) => (
<option>{row.categoryName}</option>
))}
</select>
<InputLabel id="demo-simple-select-label">Product</InputLabel>
<select className='select' >
<option>Select Product</option>
{data?.map((row: { productName: any }) => (
<option>{row.productName?.map((p: { productName: string; }) => p.productName)}</option>
))}
</select>
</div>
);
}