React+Node项目中如何将Axios响应的职位数据渲染为表格?
解决React中Axios响应数据的展示问题(列表/表格形式)
我来帮你搞定职位数据的展示!你已经成功通过Axios拿到后端返回的职位数据并存到results状态里了,接下来只需要把这个数组渲染成直观的列表或表格就行。下面是两种常用的实现方案:
方案一:列表形式展示
你可以用map()遍历results数组,把每个职位的信息以列表项的形式展示出来,同时处理搜索后无结果的情况:
<div> <h5>List of available jobs</h5> {values.results.length > 0 ? ( <ul className="list-group"> {values.results.map((job, index) => ( <li key={index} className="list-group-item"> <h6><strong>Title:</strong> {job.title}</h6> <p><strong>Category:</strong> {job.category}</p> <p><strong>Budget:</strong> {job.budget}</p> <p><strong>Duration:</strong> {job.duration} {job.durationSys}</p> <p><strong>Posted by:</strong> {job.addedBy}</p> </li> ))} </ul> ) : values.searched ? ( <p>No jobs found in this category.</p> ) : ( <p>Select a category and click search to see jobs.</p> )} </div>
方案二:表格形式展示
如果需要更规整的布局,表格是更好的选择,同样用map()渲染每一行数据:
<div> <h5>List of available jobs</h5> {values.results.length > 0 ? ( <table className="table table-striped"> <thead> <tr> <th>Title</th> <th>Category</th> <th>Budget</th> <th>Duration</th> <th>Posted By</th> </tr> </thead> <tbody> {values.results.map((job, index) => ( <tr key={index}> <td>{job.title}</td> <td>{job.category}</td> <td>{job.budget}</td> <td>{`${job.duration} ${job.durationSys}`}</td> <td>{job.addedBy}</td> </tr> ))} </tbody> </table> ) : values.searched ? ( <p>No jobs found in this category.</p> ) : ( <p>Select a category and click search to see jobs.</p> )} </div>
几个重要的细节提醒
- 替换
class为className:React中DOM元素的类名属性必须用className(你的原代码里用了class,比如<div class="form-group">,建议改成<div className="form-group">,避免控制台警告)。 - 设置唯一的
key属性:在map()渲染列表项/表格行时,最好用每个职位的唯一标识(比如后端返回的id字段)作为key,如果没有的话再用index,这样React能更高效地更新DOM。 - 更新
searched状态:在listJobs函数的then回调里,记得把searched设为true,这样才能正确显示无结果的提示:
.then(response => { console.log('LOG SUCCESS --', response.data); const data = response.data; setValues({...values, results: data, searched: true}) // 这里加上searched: true console.log('LOG STATE', data) })
把上面的代码替换你原组件里的//here部分,就能正常展示职位数据啦!
内容的提问来源于stack exchange,提问作者ephantus okumu
相关产品推荐
相关产品推荐

