如何解决嵌套数组中单个select下拉框选中值同步变化问题?
解决嵌套数组中Select选项同步变化的问题
这个问题我之前也踩过坑!你现在遇到的所有下拉框同步变化的核心原因是:用了单个状态变量quantity来控制所有下拉框的选中值。不管操作哪个下拉框,都会把同一个quantity的值改掉,自然所有绑定这个状态的下拉框都会同步更新。
解决方案:给每个下拉框分配独立的状态
我们需要把状态改成一个对象(或者数组),用来存储每个列表项对应的选中值,这样每个下拉框都有自己独立的状态,修改时只会影响当前操作的那个。
修改后的完整代码
const array = [ { thing: "itemone", thingArr: [1, 2, 3, 4] }, { thing: "itemtwo", thingArr: [1, 2, 3, 4] }, { thing: "itemthree", thingArr: [1, 2, 3, 4] }, { thing: "itemfour", thingArr: [1, 2, 3, 4] } ]; function App() { // 初始化状态:给每个item设置默认选中值1 const [quantities, setQuantities] = useState( array.reduce((acc, item) => ({...acc, [item.thing]: 1}), {}) ); // 修改状态时,根据item的thing属性定位到对应的状态项 const onSelectChange = (thing, e) => { setQuantities(prevState => ({ ...prevState, [thing]: e.target.value })); }; return ( <div className="App"> {array.map(item => ( <div key={item.thing}> <p>{item.thing}</p> <select value={quantities[item.thing]} onChange={(e) => onSelectChange(item.thing, e)} > {item.thingArr.map(option => ( <option key={option} value={option}> {option} </option> ))} </select> </div> ))} </div> ); }
关键修改点说明
- 状态结构调整:从单个变量
quantity改成对象quantities,每个键对应item.thing,值是该item下拉框的选中值,初始化时用reduce批量设置默认值1。 - 修改状态的逻辑:
onSelectChange新增thing参数,用来标识当前操作的是哪个item的下拉框,更新时只修改对应键的值,保留其他状态不变。 - 绑定下拉框:每个select的
value绑定quantities[item.thing],onChange传递当前item的thing参数,确保只更新对应状态。
这样修改后,每个下拉框的选中值就会独立变化,不会再出现同步更新的问题了~
内容的提问来源于stack exchange,提问作者mvkdiegnhoiw
相关产品推荐
相关产品推荐

