我试图在数组内迭代这个数组,但它会引发一些错误
我是这个React和JSX的新手,请帮忙解决这个问题
我的JSON数据是这样的:
[
{
"text": "Amenities",
"type": "multi",
"name": "amenities",
"value": [
{
"text": "24 Hour Checkin",
"id": 24,
"disabled": true,
"selected": true
},
{
"text": "Breakfast",
"id": 23,
"disabled": true,
"selected": true
},
{
"text": "WiFi",
"id": 22,
"disabled": true,
"selected": true
},
{
"text": "Pure Veg Restaurant",
"id": 21,
"disabled": true,
"selected": true
}
]
},
{
"name": "stayType",
"text": "Type of Stay",
"type": "multi",
"value": [
{
"text": "Hotels",
"id": 20,
"disabled": true,
"selected": true
},
{
"text": "Lodges & Guest houses",
"id": 19,
"disabled": true,
"selected": true
},
{
"text": "Resorts",
"id": 18,
"disabled": true,
"selected": true
},
{
"text": "Homestays",
"id": 19,
"disabled": true,
"selected": true
}
]
}
]
我的脚本是这样的:
const React = require('react');
const Filters = React.createClass({
render: function () {
var filtersHtml = this.state.filters.map((r, i) => {
return (
<ul className="section">
<div className="filter-heading">r.text</div>
if (r.type === 'multi') {
r.value.map((value, index) => {
<li className="pos-rel searchByNameTextBoxWrapper">
<label>{value.text}</label>
<input maxLength="50" value="" id={value.id} type="checkbox" className=""/>
</li>
});
}
else {
r.value.map((obj, key) => {
<li className="pos-rel searchByNameTextBoxWrapper">
<label>{obj.text}</label>
<input maxLength="50" value="" id={obj.id} type="radion" className=""/>
</li>
});
}
</ul>
);
});
if (this.state.filters.length) {
return (
<div className="filters-sec-wrapper">
<div className="filters-inner-sec-wrapper">
<ul className="section">
{filtersHtml}
</ul>
</div>
</div>
);
}
return (
<div className="filters-sec-wrapper">
<div className="filters-inner-sec-wrapper">
<ul className="section">
Loading
</ul>
</div>
</div>
);
}
});
module.exports = Filters;
我尝试在这里编译我的代码https://babeljs.io/repl/
答案 0 :(得分:1)
我重构了你的代码,你可以检查它(下面的例子)。
const Filters = React.createClass({
getInitialState: function () {
return { filters: this.props.filters } // just for example
},
isMulti: function (type) {
return type === 'multi';
},
filter: function (value, type) {
return <li key={ value.id } className="pos-rel searchByNameTextBoxWrapper">
<label>{ value.text }</label>
<input maxLength="50" id={ value.id } type={ type } />
</li>;
},
filters: function () {
return this.state.filters.map((r, i) => {
return <div key={ i }>
<div className="filter-heading">{ r.text }</div>
<ul className="section">
{ r.value.map((value, index) => this.filter(value, this.isMulti(r.type) ? 'checkbox' : 'radio')) }
</ul>
</div>
});
},
render: function () {
var content = (this.state.filters.length) ? this.filters() : 'Loading';
return (
<div className="filters-sec-wrapper">
<div className="filters-inner-sec-wrapper">{ content }</div>
</div>
);
}
});