我尝试了以下代码,但收到了错误。
<li>
{items.map(item =>
{item.status === 'active' ^^ <h1>{item.gender}</h1>}
<p>{item.name}</p>
}
<li>
我的json是这样的:
[{"name":"james","satus":"active"},{"name":"alice","satus":"deactived"}]
所需的输出是按状态标题分隔列表项。例如:
active
- james
- john
- mattew
deactive
- alice
答案 0 :(得分:2)
获得所需输出的一种方法是根据items
从status
数组创建两个新数组。 注意:你有一个拼写错误&#34; satus&#34; 。
为此,您可以将Array.prototype.filter与Array.prototype.map功能结合使用。这是一个演示:
var Demo = React.createClass({
_renderList: function(items, status) {
return (
<div>
<span>{status}</span>
<ul>
{items.filter(item => item.status == status).map((item, i) =>
<li key={i}>{item.name}</li>
)}
</ul>
</div>
);
},
render: function() {
var items = [{"name":"james","status":"active"},{"name":"alice","status":"deactived"}];
return (
<div>
{this._renderList(items, "active")}
{this._renderList(items, "deactived")}
</div>
);
}
});
ReactDOM.render(
<Demo />,
document.getElementById('container')
);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container"></div>
&#13;
答案 1 :(得分:0)
以下快速示例:
const ListSample = () => {
let items = [
{"name":"James","status":"active"},
{"name":"Alice","status":"deactived"},
{"name":"John","status":"deactived"},
{"name":"Joe","status":"active"},
{"name":"Ann","status":"deactived"},
{"name":"Jane","status":"active"}
];
let statusList = [];
for (let item of items) {
if (statusList.indexOf(item.status) < 0) {
statusList.push(item.status);
}
}
const renderList = (status) => {
return (
<div>
<h2>{status}</h2>
<ul>
{
items
.filter(item => item.status === status)
.map((item, i) => (<li key={i}>{item.name}</li>))
}
</ul>
</div>
);
};
return (
<div>
{ statusList.map(renderList) }
</div>
);
};
ReactDOM.render(<ListSample/>, document.getElementById('app'));
&#13;
<body>
<div id="app"></div>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</body>
&#13;
答案 2 :(得分:0)
您不需要使用两个loops
,使用两个变量active = [], deactived = []
并将活动和停用的值存储在这些变量中,并return
使用div
存储它们,检查摘录:
var a = [
{"name":"james","status":"active"},
{"name":"alice","status":"deactived"}
];
class App extends React.Component {
_createList() {
let active = [], deactived = [];
a.forEach((item,i) => {
item.status === 'active'? active.push(<li key={i}>{item.name}</li>) : deactived.push(<li key={i}>{item.name}</li>);
})
return(<div>
Active <ul> {active} </ul>
Deactivated <ul> {deactived} </ul>
</div>
)
}
render() {
return (
<div>
{this._createList()}
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='container'/>