React中如何遍历父组件传入的props动态渲染select下拉选项
问题根因
下拉框重复渲染硬编码"Agent"、无法展示props传入数据,由3处代码逻辑错误导致:
- option标签内部直接写死了文本
Agent,未读取遍历生成的agent对象的属性值,无论遍历多少条数据,每个选项都会显示固定的硬编码内容 - 处理profile数据的
useEffect依赖数组为空,仅在组件首次挂载时执行1次。如果父组件传入的profile是异步接口返回、组件挂载完成后才传值,该effect不会重新触发,agents状态始终拿不到最新props数据 - option标签的key、value属性直接绑定了整个agent对象,React列表渲染要求key为唯一基础类型值,绑定对象会引发渲染异常、选中值匹配失效问题
修复方案
- 将option标签内硬编码的
Agent替换为遍历项的实际展示字段agent.label - 给useEffect依赖数组加入
profile,保证props更新时能同步更新agents状态 - 修正option的key、value绑定逻辑,使用唯一的
agent.value作为key和option的value属性值 - 增加profile空值校验,避免profile未传入时调用map方法抛出JS报错
修复后完整代码
import React, { useState, useEffect } from 'react' import Button from '@/components/Button.jsx' import Loading from '@/components/Loading.jsx' import Modal from '@/components/Modal.jsx' /** * 新建/编辑能力项弹窗组件 * @component */ export default function AddCapabilitiesModal({ profile, onClose }) { const [error, setError] = useState(null) const [loading, setLoading] = useState(false) const [agents, setAgents] = useState([]) const [profiles, setProfiles] = useState([]) useEffect(() => { if (profile?.length) { console.log(profile); setAgents(profile.map((f) => ({ label: f.agent, value: f.agent }))) setLoading(false); } }, [profile]) /** * 清空表单状态并关闭弹窗 */ const closeModal = () => { setError(false) setLoading(false) onClose() } const dummyClick = () => { console.log('click') } return ( <div> <Modal> {error && ( <label className='high'> Error: Please confirm inputs and try again. </label> )} <div className='modal-title'> <label>EDIT STATUS</label> </div> <br /> <Loading text='Saving Test...' visible={loading} /> {!loading && ( <div id='addCapSelectInput' className='sub-filters'> <div className='lrow filter-options group light-grey-bg'> <select> {agents.map((agent) => ( <option key={agent.value} value={agent.value}> {agent.label} </option> ))} </select> </div> </div> )} <div className='modal-row top-horizontal-divider'> <Button onClick={closeModal} className='modal-cancel'> Cancel </Button> <Button onClick={dummyClick} className='modal-submit' > Submit </Button> </div> </Modal> </div> ) }
补充说明
如果原始profile数据中agent字段存在重复值,建议替换为数据中的唯一id字段作为option的key和value,避免同值选项引发选中状态冲突。
内容的提问来源于stack exchange,提问作者kjamp
相关产品推荐
相关产品推荐

