繁体   English   中英

在 ReactJs 中调用 Map 函数内的子组件

[英]Calling A Child Component Inside a Map Function In ReactJs

我有一个数组时间状态并且里面有数据。我想要做的是通过这个状态映射并使用道具调用子组件

我的状态

 this.state = { 
  user:'',
 feedArray:[],

 }

数据设定功能

  //I CALLED THIS IN COMPONENTDIDMOUNT
  renderFeed(){
  rdb.ref("feeds").once('value',(snapshot)=>{
  snapshot.forEach((childSnapshot)=>{
    this.setState({feedArray:Object.values(childSnapshot.val())})

})
 }).then(()=>{
console.log(this.state.feedArray);
})

}

退货部分

 render() { 

    if (this.state.feedArray) {
      this.state.feedArray.map((feed,id)=>{
        console.log(feed.body);   //this works fine
        return (<FeedElement id={feed.id} body={feed.body}/> );  //This Not Works

      })

    }
     }

这是在 console.log(this.state.feedArray) 上 Cosoled 的日志

(4) […]
​
0: Object { author: "AashiqOtp", body: "kkk", feedid: "-M1_6POMRyqRv2tIKrF9", … }
​
1: Object { author: "AashiqOtp", body: "kkk", feedid: "-M1_6XYaUAlsXlwnAbcp", … }
​
2: Object { author: "AashiqOtp", body: "f", feedid: "-M1_HB07eh_08OFFRBbO", … }
​
3: Object { author: "AashiqOtp", body: "we have a new rm", feedid: "-M1d4xwLmSUKA0RZlH-Q", … }

有任何想法吗? 提前致谢

您可以通过 feed.feedid 而不是 feed.id 并在 map 函数之前返回。

render() { 

if (this.state.feedArray) {
  return this.state.feedArray.map((feed,id)=>
    (<FeedElement id={feed.id} body={feed.body}/> );  //This Not Works
   )

}else {
    return null;
}
 }

希望它应该工作

this.state.feedArray.map((feed,id)=>{
        console.log(feed.body); 
        return (<FeedElement id={id} body={feed.body}/> );  Works
      })

feed.id相当于feed[id]并且如果id不存在于对象数组中,则访问它会抛出undefined ,但是从 console.log 中您提供的feed具有feed.feedid ,您可以传递id={feed.feedid}id={id}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM