渲染对象数组以在JSX中列出

我尝试将对象数组转换为列表。现在,我只想将对象的“类型”属性转换为列表项,但是它不起作用。

这是我的代码:

constructor(props){
    super(props);
    this.travelRawdata = [{type:15}];
}
render(){
    return(
        <ul>
           {this.travelRawdata.forEach(element => <li>{element.type}</li>)}
        </ul>
);}

我没有任何输出。如果我使用console.log(element.type)它效果很好,那么我认为我的HTML标签有问题吗?

再见StackExchange

forEach()将永远返回undefined您想使用.map()来将数据转换为一组react元素:

constructor(props){
    super(props);
    this.travelRawdata = [{type:15}];
}
render(){
    return (
        <ul>
           {this.travelRawdata.map(element => <li>{element.type}</li>)}
    </ul>
    );
}

注意:请确保在此处阅读列表和键。不包括该元素的键,将导致在每次更新数组时为每个元素重新渲染。

按键可帮助React识别哪些项目已更改,添加或删除。应该为数组内的元素提供键,以赋予元素稳定的标识

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章