React中<select>标签<option>选项首次选择后消失问题
问题解决:下拉菜单选择后选项消失的修复
你的问题核心是错误地覆盖了存储所有国家列表的状态:在selectCountry函数里,你用setCountries([e.target.value])把原本存所有国家数据的countries状态改成了只包含选中值的数组,导致后续渲染时没有足够的数据生成<option>标签,菜单自然变空。
修复步骤
- 新增独立的选中状态:创建
selectedCountry状态专门保存用户选中的值,和存储所有国家列表的countries状态分离。 - 修改选择事件逻辑:选择选项时更新
selectedCountry,而非修改countries。 - 设置受控下拉框:给
<select>添加value属性绑定selectedCountry,确保选中状态和视图同步。 - 调整Context传递内容:根据需求传递
countries和selectedCountry,方便子组件使用。
修复后的完整代码
import React, { useState, createContext, useEffect } from "react"; import axios from "axios"; export const CountryContext = createContext(); export default function LocationContext() { // 存储所有国家列表 const [countries, setCountries] = useState([]); // 存储选中的国家值 const [selectedCountry, setSelectedCountry] = useState(""); const options = { method: 'GET', url: 'https://unogs-unogs-v1.p.rapidapi.com/aaapi.cgi', params: { t: 'lc', q: 'available' }, headers: { 'X-RapidAPI-Key': 'X', 'X-RapidAPI-Host': 'unogs-unogs-v1.p.rapidapi.com' } }; useEffect(() => { async function getData() { try { const response = await axios(options); setCountries(response.data.ITEMS); // 可选:默认选中第一个国家 if (response.data.ITEMS.length > 0) { setSelectedCountry(response.data.ITEMS[0][1]); } } catch (e) { console.error(e); } } getData(); }, []); const selectCountry = (e) => { // 更新选中状态,不修改国家列表 setSelectedCountry(e.target.value); console.log("选中的国家值:", e.target.value); }; return ( <> <CountryContext.Provider value={{ countries, selectedCountry }}> <div className='country-selection-bar'> <h2> SELECTEER <select id='country' className='country' name='country' onChange={selectCountry} value={selectedCountry} > {countries.map((country) => ( <option value={country[1]} key={country[0]}> {country[2]} </option> ))} </select> </h2> </div> <Profile /> </CountryContext.Provider> </> ); }
关键修改说明
- 分离
countries(所有选项数据)和selectedCountry(选中值)两个状态,避免互相干扰。 <select>通过value={selectedCountry}变成受控组件,选中状态完全由React状态管理,避免视图和状态不一致。- Context现在传递的是包含两个状态的对象,子组件可以按需获取国家列表或选中值。
内容的提问来源于stack exchange,提问作者Tesse
相关产品推荐
相关产品推荐

