React项目表格警告:文本节点非法与缺失唯一key属性怎么解决
解决React表格的两个警告问题
第一个警告:Text nodes cannot appear as a child of
问题出在<tbody>标签内,products.map(...)语句末尾多了一个分号;——这个分号会被React识别为文本节点,而<table>的子节点只能是<thead>、<tbody>这类合法表格元素,不能包含独立文本节点。
解决步骤:删掉map语句结尾的分号,将))};改为))}。
第二个警告:Each child in a list should have a unique "key" prop
React渲染列表时,要求每个列表项必须添加唯一的key属性,用来追踪元素变化、避免不必要的重渲染。
解决步骤:给map生成的<tr>标签添加key属性。如果你的product对象有唯一标识(比如id字段),优先使用该值;若无唯一标识,可暂时用循环的index(注意:若列表存在排序、增删操作,用index作为key可能引发问题,建议后续给数据添加唯一id)。
修改后的完整代码
return ( <div className='container'> <table className="table"> <thead> <tr className='bg-dark text-white'> <th scope="col">#</th> <th scope="col">Product Name</th> <th scope="col">Product Number</th> <th scope="col">Color</th> <th scope="col">List Price</th> <th scope="col">Modified Date</th> <th scope="col">Action</th> </tr> </thead> <tbody> {products.map((product, index) => ( <tr key={product.id || index}> <th scope='row'>{index + 1}</th> <td>{product.name}</td> <td>{product.number}</td> <td>{product.color}</td> <td>{product.price}</td> <td>{product.date}</td> <td> <Link className='btn btn-primary m-2'><i className="fa fa-eye" aria-hidden="true"></i></Link> <Link className='btn btn-outline-primary m-2'>Edit</Link> <Link className='btn btn-danger m-2'>Delete</Link> </td> </tr> ))} </tbody> </table> <Link className='btn btn-outline-dark w-25' to='/product/add'> Add Product </Link> </div> );
内容的提问来源于stack exchange,提问作者Salome
相关产品推荐
相关产品推荐

