javascript - 包含多个数组的对象上的映射函数
问题描述
我有一个道具对象,里面有一个用户评论数组和 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}/>
解决方案
您需要将完整的对象传递给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
之间有一些关系才能正确映射数据。comment
userIds
推荐阅读
- c# - HttpResponse.TransmitFile 方法(但对于多个文件)?
- node.js - how to host angular and node js project on the shared hosting (cpanel or plesk)?
- awesome-wm - 当 input_passthrough 为真时,awesome-wm wibox 对鼠标信号没有反应
- c++ - 无法使用 CMake 编译 MagickWand
- spring-data-jpa - SimpleJdbcCall 跳过第一个输入参数
- c - 将引号中的字符串传输到 C 中的 ascii2 字节数组
- sql - 是否有任何查询我们必须只写我们不想显示的列?SQL / Laravel
- python - 熊猫按年分组,日期产生虚假值
- r - Filter_at selected columns with multiple str_detect patterns
- javascript - 更新状态使数组呈现错误