首页 > 解决方案 > 如何在单击提交时或第一次加载时设置默认选定值 - React Hook

问题描述

这是我的类别状态

const [category, setCategory] = useState('');

这是表单元素:

 <select onChange={e => setCategory(e.target.value)}>
                                        <Options options={categoryList} value={category}/>
                                        </select>

在更改值时,我正在选择类别

const handleBusinessInfoSubmit = (e) => {
        try{
            e.preventDefault();
            console.log("category selected is " +category);

        }
        catch{
            console.log("something went wrong!");
        }
    } 

当用户不更改值并点击提交时,如何设置类别状态?

作为参考,这里是类别列表,稍后将在键值对中以动态形式出现

 const categoryList = [
        {
            id: 1,
            value: 'Public Services'
        }, {
            id: 2,
            value: 'Automotive'
        }
        ];
// generate select dropdown option list dynamically
function Options({ options }) {
    return (
        options.map(option => 
                    <option key={option.id} value={option.value}>                                   
                    {option.value}
                    </option>)
                   );
        }

标签: javascriptreactjsreact-hooks

解决方案


可能我会将默认初始值添加到useStateas 而不是''

const [category, setCategory] = useState(categoryList[0]);

或者,如果数据是动态来的,那么setCategory()使用 API 结果中的值调用您希望拥有的默认值。

我希望这有帮助!


推荐阅读