我想迭代一个字典来使用React构造一个表,但是我被这个错误困住了:
PricingPlanTable.jsx:33未定义TypeError:无法读取未定义的属性“映射”
这是我的密码:
BillingAccount.jsx
import React, { PropTypes, Component } from 'react';
import PricingPlanTable from './PricingPlanTable';
export default class BillingAccount extends React.Component {
render() {
var pricingPlans = {
'planNames': ['Starter', 'Bronze', 'Silver', 'Gold', 'Enterprise'],
'planPrices': ['free', '$10', '$25', '$49', 'Contact Us'],
'planOptions': [
{'option': 'A', 'values': ['1', '2', '3', '4', '5']},
{'option': 'B', 'values': ['1', '2', '3', '4', '5']},
{'option': 'C', 'values': ['1', '2', '3', '4', '5']}
]
};
return (
<div>
<PricingPlanTable table={pricingPlans}/>
</div>
);
}
}PricingPlanTable.jsx
import React, { PropTypes, Component } from 'react';
export default class PricingPlanTable extends React.Component {
render() {
const table = this.props.table.map((table, i) => {
return (
<div key={i}>
<table>
<tbody>
<tr>
<th></th>
<th>Starter</th>
<th>Bronze</th>
<th>Silver</th>
<th>Gold</th>
<th>Enterprise</th>
</tr>
<tr>
<td></td>
<td>free</td>
<td>19€ /mo</td>
<td>79€ /mo</td>
<td>190€ /mo</td>
<td>custom</td>
</tr>
</tbody>
</table>
</div>
)})
return (
<div>
{table}
</div>
);
}
},这是我试图实现的一个模型:

PricingPlanTable.jsx有硬编码的表,但是我尝试使用React的'this.props‘功能来迭代它。我希望使用模板的框架,并使用BillingAccount.jsx文件中的pricingPlans变量填充它。
发布于 2016-07-18 17:37:10
作为道具传递的pricingPlans是一个对象,不能迭代。您需要访问定价计划中的每个对象,因为它们实际上包含一个数组并对它们进行迭代。
请查看以下关于如何使用Array.map() Objects/Array/map的文档
因此,使用当前的数据结构,您可以执行如下操作:
createHeaders() {
this.props.table.planNames.map((plan) => {
return <th>{plan}</th>
});
}
createContent() {
this.props.table.planPrices.map((price) => {
return <tr>{price}</tr>
});
}
render() {
const table = this.props.table;
return(
<table>
<tr>
{this.createHeaders}
</tr>
<tr>
{this.createContent}
</tr>
</table>
)
}发布于 2016-07-18 17:50:39
首先,您应该在planOptions中使用带有planOptions映射的数组。其次,在map中,您将一次又一次地返回表,而必须只返回行。应该是这样的。
import React, { PropTypes, Component } from 'react';
export default class PricingPlanTable extends React.Component {
render() {
const table = this.props.table.planOptions.map((obj, i) => {
return (
<tr key={i}>
<td>{obj.option}</td>
{obj.value.map(value => {
return (
<td>{value}</td>
);
})}
</tr>
)})
return (
<div>
<table>
<tbody>
<tr>
<th></th>
<th>Starter</th>
<th>Bronze</th>
<th>Silver</th>
<th>Gold</th>
<th>Enterprise</th>
</tr>
<tr>
<td></td>
<td>free</td>
<td>19€ /mo</td>
<td>79€ /mo</td>
<td>190€ /mo</td>
<td>custom</td>
</tr>
{tbody}
</tbody>
</table>
</div>
);
}
}https://stackoverflow.com/questions/38442573
复制相似问题