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

React中Dropdown默认显示预填充项而非Select的问题排查

问题根因

默认预填充选项是代码里主动设置的逻辑导致的:

  • 接口拉取问题列表成功后,写了if (i.length > 0) setQuestionDrop(i[0])逻辑,只要列表不为空就会自动把第一个选项设为选中值,此时questionDrop不再是初始的undefined,label属性的?? 'Select'兜底逻辑不会触发,直接显示第一个选项的标题。
  • 配套的第二个useEffect会在questionDrop有值时立刻触发概览接口请求,相当于页面加载完就直接拉取第一个选项的详情,和默认未选择的预期完全冲突。
修复步骤
  1. 删除自动选中首项的逻辑
    把第一个useEffect中if (i.length > 0) setQuestionDrop(i[0])这行代码删掉,接口返回列表后只更新选项数据源,不修改选中状态,此时questionDrop保持初始的undefined,下拉框默认就会显示'Select'提示。
    修改后的第一个useEffect参考:
useEffect(() => {
    ClearApi.listQuestions()
        .then(res => {
            const questionList = res.data.questions
            console.log('Questions: ', questionList)
            setQuestions(questionList.map(item => ({ ...item, value: item._id, name: item.title })))
        })
        .catch(err => {
            console.log(err)
        })
}, [])
  1. (推荐优化)补全受控组件绑定逻辑
    大部分Dropdown组件是受控模式,建议显式绑定value属性,同时优先使用组件原生的placeholder属性传入提示文本,比手动在label里写兜底判断兼容性更好,参考写法:
<Dropdown
    placeholder="Select"
    items={questions}
    value={questionDrop?._id}
    onSelect={({ value }) => setQuestionDrop(questions.find(i => i._id === value))}
/>

改完后只有用户手动选择下拉选项时,才会更新questionDrop值、触发对应的概览接口请求,默认状态就会正常显示Select提示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 10:18:06