提问者:小点点

如何设置默认的选择值时,点击提交或非常第一次,而加载-反应钩子


这是我的类别状态

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

这是form元素:

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

在更改值时,我将使category成为选中的

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

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

当用户没有更改值并点击Submit时,如何设置Category状态?

为了参考起见,下面是类别列表,它将在后面的键值对中作为动态出现

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

共1个答案

匿名用户

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

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

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

我希望这能帮上忙!