React调用Django Rest API渲染表格表头重复问题求助
解决React渲染表格时表头重复的问题
嗨,我一眼就看出问题所在啦!你现在把整个<table>标签都放在了this.state.todos.map()的循环里,这就意味着每一条产品数据都会生成一个完整的表格——表头自然就跟着重复出现了,3条数据就有3个表头,和你描述的完全一致。
要解决这个问题很简单,我们只需要让**表格行(<tr>)**进入循环,而整个表格(包括表头)只渲染一次就行。调整后的代码结构应该是这样的:
import React, { Component } from 'react'; class Products extends Component { state = { todos: [] }; async componentDidMount() { try { const res = await fetch('http://127.0.0.1:8000/api/'); const todos = await res.json(); this.setState({ todos }); } catch (e) { console.log(e); } } render() { return ( <div> {/* 整个表格只渲染一次 */} <table className="table table-bordered table-hover table-striped"> <thead> <tr className="bg-gray text-white"> <th>Id</th> <th>Category</th> <th>Name</th> <th>Short Description</th> <th>Price</th> <th className="text-center">Image</th> <th>Delete</th> </tr> </thead> <tbody> {/* 只循环表格行 */} {this.state.todos.map(item => ( <tr key={item.id}> {/* 注意要加唯一的key属性,React要求列表元素必须有key */} <td scope="row">{item.id}</td> {/* 这里你原来写的是item.title,对应Id列改成item.id更合理哦 */} <td>{item.category}</td> <td>{item.name}</td> <td>{item.short_description}</td> <td>{item.price}</td> <td className="text-center"> {/* 如果API返回图片地址,可以在这里渲染,比如 <img src={item.image} alt={item.name} /> */} </td> <td>Delete</td> </tr> ))} </tbody> </table> </div> ); } } export default Products;
我还帮你修正了几个容易踩坑的小细节:
- React的JSX语法里要用
className代替原生HTML的class,不然会有语法警告; - 给循环的
<tr>加上了key属性,这是React列表渲染的强制要求,能避免性能警告; - 把你原来空着的
<td>填上了对应字段(你可以根据API实际返回的字段名调整); - 去掉了原来
<td>后面多余的逗号,JSX元素后不能加逗号,这也是你之前移动循环位置报错的可能原因之一。
这样调整后,整个表格只会渲染一次表头,<tbody>里的每一行对应一条产品数据,就不会出现重复表头的问题啦!
内容的提问来源于stack exchange,提问作者Mickael Zana
相关产品推荐
相关产品推荐

