React中state数组map遍历console.log正常但<span>不渲染问题排查
问题根源:Map回调缺少返回值
你的问题其实很典型——你在map的回调函数里写了JSX,但没有把它返回出去!
虽然console.log(item.id)能正常执行,说明数组确实在遍历,但React需要你把要渲染的元素从map回调里返回,才会把它们加入到DOM树中。看你的代码,map里的箭头函数用了花括号{},但没有写return语句,所以默认返回undefined,自然不会有任何元素渲染出来。
两种修复方式:
1. 显式添加return
把JSX用return包裹起来:
<p>Recently printed plates</p> <p>{this.state.plateHistory.length > 0 ? this.state.plateHistory[0].id : 'Nope'}</p> {this.state.plateHistory.map((item, i) => { // 这里加上return return ( <div key={i}> {/* 记得给map的元素加key,这是React的要求 */} <span>{item.id}</span> <div className="col-lg-6 text-center" style={divStyle}> <span>{item.id}</span> {console.log(item.id)} </div> </div> ) })}
2. 改用箭头函数的隐式返回
如果箭头函数直接返回表达式,可以去掉花括号,改用圆括号包裹JSX(圆括号能让JSX被识别为一个整体表达式):
<p>Recently printed plates</p> <p>{this.state.plateHistory.length > 0 ? this.state.plateHistory[0].id : 'Nope'}</p> {this.state.plateHistory.map((item, i) => ( // 这里用圆括号代替花括号,隐式返回 <div key={i}> <span>{item.id}</span> <div className="col-lg-6 text-center" style={divStyle}> <span>{item.id}</span> {console.log(item.id)} </div> </div> ))}
额外提醒:
别忘了给map生成的每个元素加上唯一的key属性,这是React优化渲染的必要条件,避免控制台警告。这里用i(索引)作为临时方案没问题,如果item.id是唯一值,用item.id会更好。
你提到this.state.plateHistory.length能正常变化,说明state更新是没问题的,就是差了这一步返回JSX,补上之后应该就能正常渲染了!
内容的提问来源于stack exchange,提问作者Craig
相关产品推荐
相关产品推荐

