首页 > 解决方案 > 包含多个数组的对象上的映射函数

问题描述

我有一个道具对象,里面有一个用户评论数组和 userId 数组。最初我只有用户评论数组,所以我使用 map 函数单独设置每个评论的样式。现在我的 props 对象中有两个数组,有没有办法使用 map 函数同时设置用户评论和他的 id 样式?这是我的尝试,但它不起作用:

import React from 'react'
import faker from 'faker'

const UserComment = (props)=> {
    var commentData = props.map(props=> {
        return(<StyleComment comment = {props.comment} key = {props.comment} author = {props.userIds} />)})

    return(null)//commentData)
}


const StyleComment = (props) => {
    // get time of comment

    return(
        <div className = 'comment'> 

                        <a href="/" className= "avatar"> 
                            <img alt ="avatar" src= {faker.image.avatar()}/>
                        </a>

                    <div className = 'name'>
                        <a href ="/" className = "author">
                            {props.author}
                        </a> 
                        <span className="metadata"> Today at 1.00pm </span>
                        <div className= 'content'>
                            <div className = 'text'>{props.comment}</div>
                        </div>
                    </div>
                </div>
    )
}

这是定义 props 的父级:

<UserComment comment = {this.state.usersComment} userIds = {this.props.userIds}/>

这是console.logprops 对象的示例输出: 控制台日志

标签: javascriptarraysreactjsmap-function

解决方案


您需要将完整的对象传递给UserComment组件,

<UserComment comment={this.state.usersComment} />

然后你可以像这样迭代,

const UserComment = (props)=> {
  console.log(props.comment);
    return props.comment.comment.map((comment,index) => {
            return <StyleComment key={comment} comment={comment} author={props.comment.userIds[index]}/>
    });
}

演示

注意:当前数组迭代和映射是基于 的,但是你必须在和数组index之间有一些关系才能正确映射数据。commentuserIds


推荐阅读