簡體   English   中英

如何使用map函數在數組中僅返回一項

[英]How to return only 1 item in an array in react using map function

當前,當用戶單擊特定主題時,它將返回數組中的所有項目。 但是,我想傳遞鍵並僅返回map函數中對象內的特定項目。 我嘗試將index作為參數傳遞,但似乎不起作用。

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>
        );
    }
});

最好使用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>
        );
    }
});

我相信您已經找到了想要的東西,但是,我看到了這個問題,但仍然沒有答案。

您只需要在映射外定義一個變量,然后在映射時,放置一個if條件以查找所需內容,然后將結果均衡到外部變量。

喜歡,

    let tmpItem;
    this.state.newOrder.map((mapItem) => {
        if (mapItem.id == "99") {
            console.log(mapItem)
            tmpItem = mapItem;
        }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM