React+TypeScript下拉选择器数据过滤失效:onChange值为undefined问题
问题解决
为什么e.target.value是undefined?
你用的是Material-UI的Select组件,它的onChange回调和原生HTML的select行为不同。原生组件可以直接通过e.target.value获取选中值,但MUI的Select封装后,回调的第二个参数才是选中的新值,直接取e.target.value会因为组件内部封装逻辑导致undefined。
修复步骤
1. 修正Select的onChange事件
把原来的回调改成接收第二个参数newValue:
<Select value={selectedType} onChange={(e, newValue) => setSelectedType(newValue)} id="type" > <option value="mtb">MTB bike</option> <option value="country">Country</option> </Select>
这是MUI官方推荐的写法,能稳定获取选中值。
2. 修复产品列表逻辑(可选但必要)
你当前的逻辑是:选中类型时只过滤不分页,未选中时只分页不过滤,这不符合常规需求。应该先过滤产品,再对过滤后的结果做分页:
// 先过滤 const filteredProducts = selectedType ? products.filter(item => item.type === selectedType) : products; // 再分页 const currentProducts = filteredProducts.slice(startIndex, startIndex + productsPerPage);
这样用户选择类型后,依然能看到分页后的过滤结果,而不是一次性加载所有匹配的产品。
3. 状态初始化验证
确保selectedType的初始值和option的value类型一致,你当前用useState("")是正确的,和option的字符串值匹配,不会出现类型不兼容的问题。
完整修正后的核心代码片段
const [selectedType, setSelectedType] = useState(""); const [startIndex, setStartIndex] = useState(0); const productsPerPage = 3; // 合并过滤与分页逻辑 const filteredProducts = selectedType ? products.filter(item => item.type === selectedType) : products; const currentProducts = filteredProducts.slice(startIndex, startIndex + productsPerPage); // 渲染Select组件 <FormControl> <FormLabel htmlFor="type">Type</FormLabel> <Select value={selectedType} onChange={(e, newValue) => setSelectedType(newValue)} id="type" > <option value="mtb">MTB bike</option> <option value="country">Country</option> </Select> </FormControl> // 渲染产品列表 <Box className="grid grid-cols-3 gap-6"> {currentProducts.map((data) => ( <Card key={data.id} maxW="sm"> {/* 产品内容 */} <span>Price: ${data.price}</span> <span>Type: {data.type}</span> </Card> ))} </Box>
内容的提问来源于stack exchange,提问作者Silo
相关产品推荐
相关产品推荐

