限制后映射结果

时间:2017-12-17 16:07:23

标签: javascript arrays reactjs

我有一个对象数组,我正在映射,然后返回一个组件,如果它与一个id(<AttachedComment />)匹配。此设置按预期使用下面的代码工作,但是,我想将后映射结果限制为仅前三个项目。预映射切片不是正确的方法,因为它在id匹配之前限制了数组量。有没有一种很好的方法来切片后映射数组?

原始阵列图:

{ this.props.comments.map((comment, i) =>
                    <AttachedComment key={comment.recordCommentId} deleteCommentFunc={this.props.deleteCommentFunc} commentObj={comment} recordComponentId={this.props.recordId} userId={this.props.user} csrf={this.props.csrf}/>
                    )}

AttachedComment

const AttachedComment = props => {
    if(props.commentObj.recordIdHash == props.recordComponentId){
        return (
            <Comment {...props.commentObj} deleteCommentFunc={props.deleteCommentFunc} key={props.commentObj.recordCommentId} currentUserId={props.userId} csrf={props.csrf}/>
            )
    } else {
        return null;
    }
}

2 个答案:

答案 0 :(得分:1)

首先在render方法开始时过滤掉你想要的注释并将其分配给一个新数组。接下来在映射操作之前对结果进行切片,如下所示。

注意:如果您使用以下方法,则不需要AttachedComment组件中的if条件

render() {
    const filteredList = this.props.comments.filter((comment) => comment.recordIdHash === this.props.recordId);

    return (
        <div>
            {filteredList.slice(0, 3).map((comment, i) =>
                <AttachedComment key={comment.recordCommentId} deleteCommentFunc={this.props.deleteCommentFunc}
                                 commentObj={comment} recordComponentId={this.props.recordId}
                                 userId={this.props.user} csrf={this.props.csrf}/>
            )}
        </div>
    );
}

答案 1 :(得分:0)

        let counter;
        const AttachedComment = props => {
        if(props.commentObj.recordIdHash == props.recordComponentId && counter < 4){
            return (
                 counter++
                <Comment {...props.commentObj} deleteCommentFunc={props.deleteCommentFunc} key={props.commentObj.recordCommentId} currentUserId={props.userId} csrf={props.csrf}/>

                )
        } else {
            return counter = 0;
        }
    }