我如何使用 React 列出 table 中的元素?
How do I list elements in the table with React?
我是 React 新手。如何使用 "map" 函数在两列中列出来自两个不同数组的元素?
state = {
dates: ["2000", "2001", "2002"],
cases: ["1", "2", "3"]
}
render() {
return (
<thead>
<tr>
<th>Date</th>
<th>Cases</th>
</tr>
</thead>
<tbody>
{this.state.dates.map(el =>
<tr>
<td>{el}</td>
</tr>
)} // I want to list elements from "cases" array like this but in the second column
</tbody>
)
}
快速简便的解决方案: 不推荐
如果您总是假设 dates
和 cases
的长度始终相同,那么您可以这样做:
{this.state.dates.map((el, index) => (
<tr>
<td>{this.state.dates[index]}</td>
<td>{this.state.cases[index]}</td>
</tr>
))}
此方法使用 map
函数的 index
参数。然后你可以在提到的特定索引处访问数组。
推荐方案:
通常的做法是按记录对数据进行分组。
使用您的示例,使用如下结构:
state = {
records: [
{ date: '2000', caseId: '1' },
{ date: '2001', caseId: '2' },
{ date: '2002', caseId: '3' }
],
}
然后这样实现:
{this.state.records.map(({ date, caseId }) => (
<tr>
<td>{date}</td>
<td>{caseId}</td>
</tr>
))}
我使用 caseId
而不是 case
因为 case
是 JavaScript 中用于 switch
语句的保留字。
您可以使用地图函数中的 index
参数并访问案例数组
<tbody>
{this.state.dates.map((el, index) => (
<tr>
<td>{el}</td>
<td>{this.state.cases[index]}</td>
</tr>
))}{" "}
</tbody>;
我是 React 新手。如何使用 "map" 函数在两列中列出来自两个不同数组的元素?
state = {
dates: ["2000", "2001", "2002"],
cases: ["1", "2", "3"]
}
render() {
return (
<thead>
<tr>
<th>Date</th>
<th>Cases</th>
</tr>
</thead>
<tbody>
{this.state.dates.map(el =>
<tr>
<td>{el}</td>
</tr>
)} // I want to list elements from "cases" array like this but in the second column
</tbody>
)
}
快速简便的解决方案: 不推荐
如果您总是假设 dates
和 cases
的长度始终相同,那么您可以这样做:
{this.state.dates.map((el, index) => (
<tr>
<td>{this.state.dates[index]}</td>
<td>{this.state.cases[index]}</td>
</tr>
))}
此方法使用 map
函数的 index
参数。然后你可以在提到的特定索引处访问数组。
推荐方案:
通常的做法是按记录对数据进行分组。
使用您的示例,使用如下结构:
state = {
records: [
{ date: '2000', caseId: '1' },
{ date: '2001', caseId: '2' },
{ date: '2002', caseId: '3' }
],
}
然后这样实现:
{this.state.records.map(({ date, caseId }) => (
<tr>
<td>{date}</td>
<td>{caseId}</td>
</tr>
))}
我使用 caseId
而不是 case
因为 case
是 JavaScript 中用于 switch
语句的保留字。
您可以使用地图函数中的 index
参数并访问案例数组
<tbody>
{this.state.dates.map((el, index) => (
<tr>
<td>{el}</td>
<td>{this.state.cases[index]}</td>
</tr>
))}{" "}
</tbody>;