React如何渲染指定键的对象数组,仅展示name与image字段内容
问题原因&修复方案
1. 条件判断逻辑倒置
你当前代码的判断逻辑完全写反:当bestSellerCategories数组有数据(length>0)时,你只返回了带<h1>reactjs</h1>的容器,没有渲染你生成的列表项;只有数组为空时才会尝试渲染列表,自然看不到正常的name内容。
2. render调用语法错误
你的根render方法写法不符合JSX语法规范:return( {this.renderBestSellerCategories()} )里的{}会被识别为对象字面量,而非JSX插值表达式,会直接触发语法报错。
修复后代码(同时展示name+image字段)
先修改renderBestSellerCategories方法:
renderBestSellerCategories(){ console.log('aaa', this.bestSellerCategories); // 有数据时渲染列表 if(this.bestSellerCategories.length) { const listItems = this.bestSellerCategories.map((d) => ( <li key={d.name}> <p>{d.name}</p> {/* 渲染对应image字段,alt用name即可,样式可根据需求调整 */} <img src={d.image} alt={d.name} style={{width: '100px', height: '100px', objectFit: 'cover'}} /> </li> )); return( <div> <h1>reactjs</h1> <ul>{listItems}</ul> </div> ) } // 无数据时返回空提示或者空容器 else{ return( <div>暂无分类数据</div> ) } }
再修改根render方法:
render(){ // 外层包根标签后再插入方法返回的内容即可 return <div>{this.renderBestSellerCategories()}</div> }
内容的提问来源于stack exchange,提问作者michael
相关产品推荐
相关产品推荐

