React中.map()无法渲染列表项,仅表头显示问题求助
问题:React表格仅显示表头,数据行无法渲染
我几乎复用了现有文件的完全相同代码,尝试用map渲染表格数据,但只有表头显示。我确认数据库调用没问题,因为能在组件状态purchases中看到数据,附上代码却找不到无法渲染的原因。
var navigate = useNavigate(); // refundable purchases const [purchases, setPurchases] = useState([]); // current balance const [balance, setBalance] = useState(0); const Purchase = (props) => { // on click open interactive pop up confirming refund <tr> <td className='table-data'>{props.purchase.title}</td> <td className='table-data'>{numberFormat(props.purchase.amount)}</td> </tr> }; useEffect(()=> { async function fetchData(){ const purchaseResponse = await fetch(`http://localhost:4000/refund/`); if (!purchaseResponse.ok){ window.alert(`An error occured: ${purchaseResponse.statusText}.`) return; } const data = await purchaseResponse.json(); setPurchases(data); } fetchData(); return; },[purchases.length]); function makeTable(){ return purchases.map((element)=> { console.log(element); return ( <Purchase purchase={element} key = {element._id} /> ); }); } return ( // Will Display <section> <div className='home'> {/* Title */} <h1 className='hometitle'> Claim A Refund </h1> {/* Table of Clickable elements showing possilbe purchase refunds*/} <div> <table className='table' style={{marginTop:20}}> <thead className='table-data'> <tr> <th className='table-header'>Title</th> <th className='table-header'>Amount</th> </tr> </thead> <tbody>{makeTable()}</tbody> </table> </div> {/* On selection of specific purchase : -> double check with user -> diplay alert box containing "Refund for <transaction title> made" */} </div> </section> );
解决方法
核心问题是Purchase组件没有返回JSX元素:你的Purchase组件用了多行箭头函数,但没有显式写return,导致组件默认返回undefined,自然渲染不出任何内容。
修改Purchase组件,添加return关键字:
const Purchase = (props) => { // on click open interactive pop up confirming refund return ( <tr> <td className='table-data'>{props.purchase.title}</td> <td className='table-data'>{numberFormat(props.purchase.amount)}</td> </tr> ); };
另外注意useEffect的依赖项用purchases.length会触发无限循环:当purchases更新时,purchases.length变化,触发useEffect重新执行,再次调用setPurchases,又导致length变化。建议把依赖项改成空数组[],这样只在组件挂载时请求一次数据:
useEffect(()=> { async function fetchData(){ const purchaseResponse = await fetch(`http://localhost:4000/refund/`); if (!purchaseResponse.ok){ window.alert(`An error occured: ${purchaseResponse.statusText}.`) return; } const data = await purchaseResponse.json(); setPurchases(data); } fetchData(); }, []); // 空数组作为依赖,仅挂载时执行
内容的提问来源于stack exchange,提问作者justin.cote
相关产品推荐
相关产品推荐

