React表格创建报错:row.map is not a function问题求助
Fixing "row.map is not a function" in Your React Table
Hey there, let's break down why you're hitting this error and fix your code properly. That row.map is not a function message tells us one of the items in your tableData array isn't an array itself—so when you try to call .map() on it, JavaScript throws a fit. Let's go through the issues one by one:
Key Problems in Your Code
- Initial
tableDataentry is an object, not an array: You started withvar tableData = [ {name: this.state.users} ];—the first element here is an object, not an array of users. When your outer.map()hits this object, it can't run.map()on it, hence the error. - Typo:
lenght→length: You wrotethis.state.users.lenghtinstead ofthis.state.users.length—this would make your loop condition fail entirely (sincelenghtis undefined). - Loop starts at index 1: Arrays are zero-indexed, so starting at
x=1means you're skipping the first user inthis.state.users. - Unfinished rows get dropped: If your total number of users isn't a multiple of 4, the remaining users in
tableRownever get added totableData. - Rendering raw user objects: You're trying to render the entire user object in
<td>s, which will just show[object Object]instead of the actual name.
Corrected Code
Here's the fixed version with explanations in comments:
render() { const { users } = this.state; // Destructure for cleaner code const tableData = []; let tableRow = []; // Loop through all users (zero-indexed) for (let x = 0; x < users.length; x++) { // Push the user's name (not the whole object) into the row tableRow.push(users[x].name); // Add row to tableData when we hit 4 items, or it's the last user if ((x + 1) % 4 === 0 || x === users.length - 1) { tableData.push(tableRow); tableRow = []; // Reset row for next set } } return ( <Table1> {tableData.map((row, rowIndex) => ( <tr key={`row_${rowIndex}`}> {row.map((cell, cellIndex) => ( <td key={`cell_${rowIndex}_${cellIndex}`}>{cell}</td> ))} </tr> ))} </Table1> ); }
What Changed?
- Removed the invalid initial object from
tableData—now it starts empty, so all entries are arrays of user names. - Fixed the
lengthtypo so the loop runs correctly. - Started the loop at index 0 to include all users.
- Added a check for the last user to make sure we don't drop any remaining items in
tableRow. - Rendered
users[x].nameinstead of the whole object so you see actual text in the table cells. - Improved key props using more unique identifiers (combining row and cell indexes) to avoid React warnings.
This should eliminate the row.map is not a function error and render your table correctly!
内容的提问来源于stack exchange,提问作者jj.badweyn
相关产品推荐
相关产品推荐

