【问题标题】:How to set array to state of component in ReactJS? [duplicate]如何在 ReactJS 中将数组设置为组件的状态? [复制]
【发布时间】:2018-10-21 00:02:07
【问题描述】:

当我在 ReactJS 中渲染它时,我收到错误消息:“对象作为 React 子级无效(找到:带有键 {Source, Value} 的对象)。如果您要渲染一组子级,请使用数组反而。”。但在我的初始状态下,我将键“list_ratings”初始化为一个数组。

// this is in my constructor method
this.state = {list_ratings: []}

// this is somewhere else in my code    
let movieRatings = [
                            {"Source": "IMDB", "Value": "8"},
                            {"Source": "GDN", "Value": "6"},
                            {"Source": "The times", "Value": "7"}
                        ];

                        this.setState({
                            list_ratings: movieRatings
                        });

我该如何解决这个问题?

我将评分列表呈现如下:

<p>{this.state.list_ratings}</p>

【问题讨论】:

  • 你如何渲染list_ratings
  • @madox2 我更新了我的帖子

标签: javascript reactjs


【解决方案1】:

您尝试渲染无效的普通对象:

<div>
  <p>{this.state.list_ratings}</p>
</div>

通过渲染一些有效的东西来修复它,比如键字符串:

<p>{this.state.list_ratings[0].Source + " " + this.state.list_ratings[0].Value}</p>

map整个列表:

<div>
  {
    this.state.list_ratings.map(lR => 
     <p key={lR.Value}>{lR.Source + " " + lR.Value}</p>
    )
  }
</div>

【讨论】:

    【解决方案2】:

    你需要在movieRatings上使用map,遍历每个对象

     const movieRatingsList = movieRatings.map((movieRating, i) =>
        <li key={i}> {movieRating.Source} : {movieRating.Value}  </li>
      );
    
    
    render(){
     return(
       {this.movieRatingsList()}
     )
    }
    

    【讨论】:

    • 需要封装渲染函数
    猜你喜欢
    • 2019-08-16
    • 2021-08-03
    • 2016-06-09
    • 2022-07-07
    • 2020-12-14
    • 2018-04-29
    • 2017-11-17
    • 2015-06-08
    • 2023-03-27
    相关资源
    最近更新 更多