繁体   English   中英

遍历对象React

[英]Loop through objects React

我的React组件具有以下渲染

componentWillMount () {
    var url = 'https://gist.githubusercontent.com/hart88/198f29ec5114a3ec3460/raw'
    Request.get(url)
    .then(data => {
        this.setState({cakes: data.text});
    })
}

render() {
    return(
        <div>
            {this.state.cakes} //prints this ok

            {
              this.state.cakes.map(cake =>{ // error here
                return <p>{cake.title}</p>;
              })
            }
        </div>
    );
}

我试图遍历this.state.cakes这是一个对象数组。

我在这里做错了什么?

更新this.state.cakes的缩写示例:

[
    {
        "title": "Lemon cheesecake",
        "desc": "A cheesecake made of lemon",
        "image":"https://s3-eu-west-1.amazonaws.com/s3.mediafileserver.co.uk/carnation/WebFiles/RecipeImages/lemoncheesecake_lg.jpg"
    },
    {
        "title":"Banana cake",
        "desc":"Donkey kongs favourite", 
         "image":"http://ukcdn.ar-cdn.com/recipes/xlarge/ff22df7f-dbcd-4a09-81f7-9c1d8395d936.jpg"
    }
]

谢谢

我相信您已经使用了花括号(可以理解),其中React实际上需要括号。 由于您是从fetch数据的,因此请务必将构造函数也设置为“ cakes初步对象。 尝试这个:

constructor(props) {
    super(props)
    this.state = {
        cakes: []
    }
}

render() {
    if (this.state.cakes.length > 0){
        return(
            <div>
                {
                    this.state.cakes.map(cake => (
                        return <p>{cake.title}</p>;
                    ))
                }
            </div>
        );
    }

    return null
}

问题是,该组件被渲染和你告诉它做称为数组的东西this.state.cakes ,但this.state.cakes尚未确定,因为fetch还没有恢复。 像这样设置构造函数,会将一个空数组传递给render这样它就不会崩溃,然后在数据加载和状态更新时,它将随数据一起重新渲染。

{this.state.cakes}本身可以很好地渲染的原因是,对于组件存在的第一{this.state.cakes} ,该值是undefined ,这意味着React基本上只是忽略了它-数据加载后,呈现。 但是, map方法失败,因为您无法将未定义的数组传递给map

正如Ha Ja所建议的那样,您可能应该在<p>元素中添加一个key属性。

这里:

{this.state.cakes.map((cake, i) => <p key={i}>{cake.title}</p>;)}

不要忘记添加key属性。 Ps:最好使用唯一的Id代替数组索引。 因此,如果您对每个数组项都有一个ID,最好这样写:

{this.state.cakes.map(cake => <p key={cake.id}>{cake.title}</p>;)}

如果将状态设置为获取的结果,则由于异步操作,您可能无法立即访问数据。 您可以通过检查状态来捕获此错误,如果状态没有长度,则返回一条消息或微调器组件以指示数据的状态。

一旦使用获取操作中的数据更新state.cakes ,该组件将重新呈现。

constructor(props) {
  super(props);
  this.state = { cakes: [] };
}

componentDidMount() {
  fetch('/cakes')
    .then(res => res.json())
    .then(cakes => this.setState({ cakes }));
}

render() {
  if (!this.state.cakes.length) return <Spinner />
  return (
    <div>
      {this.state.cakes.map(cake => {
        return <p>{cake.title}</p>;
      })};
    </div>
  )
}

正如其他人所提到的,将key添加到迭代元素中也是一种好习惯。

您错过了map内的括号

    {this.state.cakes.map(cake =>{ // errors here
        return <p> {cake.title} </p>;
    })}

暂无
暂无

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

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