目前,当用户点击某个特定主题时,它会返回数组中的所有项目。但是,我想传递键,只返回map函数中对象内的特定项。我尝试将索引作为参数传递,但它似乎不起作用。
var topicPages = [
{
topic_no: '1',
topic_page_no: '1',
headline: 'Topic 1 headline',
description: 'Topic 1 description comes here...',
first_topic_page: true,
last_topic_page: false
},
{
topic_no: '2',
topic_page_no: '2',
headline: 'Topic 2 headline',
description: 'Topic 2 description comes here...',
first_topic_page: false,
last_topic_page: false
},
{
topic_no: '3',
topic_page_no: '3',
headline: 'Topic 3 headline',
description: 'Topic 3 description comes here...',
first_topic_page: false,
last_topic_page: false
},
{
topic_no: '4',
topic_page_no: '4',
headline: 'Topic 4 headline',
description: 'Topic 4 description comes here...',
first_topic_page: false,
last_topic_page: true
}
];
var SelectedTopicPage = React.createClass({
render: function() {
return (
<div>
{this.props.topicPages.map(function (topicPage) {
return (
<SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
{topicPage.description}
</SelectedTopicPageMarkup>
);
})}
</div>
);
}
});
var SelectedTopicPageMarkup = React.createClass({
render: function() {
return (
<div className="topics-page">
<h1>{this.props.headline}</h1>
<p>{this.props.children}</p>
</div>
);
}
});
答案 0 :(得分:1)
最好使用find
,但并非所有浏览器都支持此功能。使用reduce
代替map
:
var SelectedTopicPage = React.createClass({
render: function() {
var selectedId = this.props.selectedId; // id what you need to find
var topicPage = this.props.topicPages.reduce(function(topic, current) {
return topic.topic_no == selectedId ? current : topic;
}, undefined);
return (
<SelectedTopicPageMarkup headline={topicPage.headline} key={topicPage.topic_no}>
{topicPage.description}
</SelectedTopicPageMarkup>
);
}
});
答案 1 :(得分:1)
我相信您已经找到了想要的东西,但是, 我看到了这个问题,但仍然没有答案。
您只需要在映射外部定义一个变量,而在映射时,将一个if条件放入要查找的内容中,然后将结果与外部变量相等。
就像
let tmpItem;
this.state.newOrder.map((mapItem) => {
if (mapItem.id == "99") {
console.log(mapItem)
tmpItem = mapItem;
}
});