MERN项目中ReactJS如何将MongoDB后端获取的数据渲染为表格
修正后完整代码
import React from 'react'; import axios from 'axios'; class Admin extends React.Component { state = { phone: '', email: '', posts: [] }; hello = () => { axios.get('/getuser') .then((response) => { const data = response.data; this.setState({ posts: data }); console.log(data); }) .catch(() => { alert('数据获取失败!!!'); }); } displayBlogPost = (posts) => { if (!posts.length) return <p className="text-muted">暂无用户数据,请点击上方按钮获取</p>; return ( <div className="blog-post__display"> <table className="table table-striped table-sm"> <thead> <tr> <th>邮箱</th> <th>手机号</th> </tr> </thead> <tbody> {posts.map((post, index) => ( <tr key={index}> <td>{post.email}</td> <td>{post.phone}</td> </tr> ))} </tbody> </table> </div> ); }; render() { return ( <> <h1> <button onClick={this.hello} className="btn btn-danger">点击获取数据</button> </h1> <div className="blog-container"> {this.displayBlogPost(this.state.posts)} </div> </> ) } } export default Admin;
核心修改说明
- 调整表格结构:将表格整体、表头移出数据循环,仅对表格数据行做map遍历,避免每条数据生成独立的表格
- 修正字段绑定错误:原代码第二列错误绑定了email字段,改为对应
phone字段 - 规范React属性:将原生HTML的
class属性全部替换为React要求的className属性,避免属性不生效问题 - 补充语义化标签:增加
<thead>、<tbody>标签,符合HTML规范,也方便后续样式调整 - 优化空状态展示:未获取到数据时展示友好提示,而非空白内容
- 优化文案展示:将按钮、提示文案改为中文,符合使用习惯
内容的提问来源于stack exchange,提问作者user14110207
相关产品推荐
相关产品推荐

