【问题标题】:Calling A Child Component Inside a Map Function In ReactJs在 ReactJs 的映射函数中调用子组件
【发布时间】:2020-06-17 17:03:04
【问题描述】:

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

我的状态

 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

      })

    }
     }

这是consoled on console.log(this.state.feedArray)的日志

(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", … }

有什么想法吗?提前致谢

【问题讨论】:

  • 不需要if,在map之前添加return
  • 显示错误:期望赋值或函数调用,而是在 return() 中看到一个表达式 no-unused-expressions 包装 map 函数

标签: javascript arrays reactjs javascript-objects map-function


【解决方案1】:

你能不能传递 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;
}
 }

希望它应该工作

【讨论】:

  • 这里不需要else,但如果你喜欢它也没有什么坏处。
  • else 是必需的,因为如果 this.state.feedArray 为 false 或 null 或未定义,那么它会抛出错误,因为渲染需要返回,但没有 else 它不会返回任何东西,它会给出错误跨度>
【解决方案2】:
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 中feedfeed.feedid,你可以通过id={feed.feedid}id={id}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-02
    • 1970-01-01
    • 2017-12-26
    • 2021-12-26
    • 2020-08-14
    • 2020-12-27
    • 1970-01-01
    • 2021-04-14
    相关资源
    最近更新 更多