React列表渲染失效求助:手动添加正常,map遍历无效果
问题排查:React map遍历列表不显示的原因
你的问题出在map的回调函数里——你用大括号包裹了逻辑,但没有显式返回<li>元素。React中,箭头函数用大括号时必须手动写return才能返回渲染内容,否则默认返回undefined,自然不会渲染任何列表项。
两种修复方案:
方案1:添加显式return语句
import './App.css' const App = () => { return ( <div className="App"> <ul> {items.map((item, index) => { // 显式返回li元素 return <li key={index}><span>{item.title}</span></li> })} </ul> </div> ); } export default App; const items = [ { title: "asd0", image: "" }, { title: "asd1", image: "" }, { title: "asd2", image: "" } ]
方案2:改用箭头函数隐式返回(替换大括号为小括号)
import './App.css' const App = () => { return ( <div className="App"> <ul> // 用小括号实现隐式返回,无需写return {items.map((item, index) => ( <li key={index}><span>{item.title}</span></li> ))} </ul> </div> ); } export default App; const items = [ { title: "asd0", image: "" }, { title: "asd1", image: "" }, { title: "asd2", image: "" } ]
额外建议
如果items中的元素有唯一标识(比如id字段),尽量用这个唯一值作为key,而不是index——用index当key在列表元素顺序变化时,可能引发渲染性能问题或组件状态异常。
内容的提问来源于stack exchange,提问作者MATEQH_
相关产品推荐
相关产品推荐

