在React中渲染array.map() [英] Rendering an array.map() in React

查看:100
本文介绍了在React中渲染array.map()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在尝试使用数据数组呈现<ul>元素时遇到问题.在console.log下方的代码中,它们可以正常工作,但没有显示列表项.

I am having a problem where I am trying to use array of data to render a <ul> element. In the code below the console.log's are working fine, but the list items aren't appearing.

var Main = React.createClass({
  getInitialState: function(){
    return {
      data: dataRecent
    }
  },

  render: function(){
    return (
      <div>
        <ul>
          {
           this.state.data.map(function(item, i){
             console.log('test');
             <li>Test</li>
           })
         }
        </ul>
      </div>
    )
  }
});

ReactDOM.render(<Main />, document.getElementById('app')); 

我做错了什么?请随时指出并非最佳做法的任何地方.

What am I doing wrong? Please feel free to point out anything that isn't best practice.

推荐答案

Gosha Arinich 是正确的,您应该返回<li>元素. 但是,在这种情况下,您仍然应该在浏览器控制台中收到讨厌的红色警告

Gosha Arinich is right, you should return your <li> element. But, nevertheless, you should get nasty red warning in the browser console in this case

数组或迭代器中的每个子代都应具有唯一的键".道具.

Each child in an array or iterator should have a unique "key" prop.

因此,您需要添加"key"到您的列表:

so, you need to add "key" to your list:

this.state.data.map(function(item, i){
  console.log('test');
  return <li key={i}>Test</li>
})

或放下console.log()并使用es6

or drop the console.log() and do a beautiful oneliner, using es6 arrow functions:

this.state.data.map((item,i) => <li key={i}>Test</li>)

重要更新:

上面的答案正在解决当前的问题,但正如注释中提到的 Sergey 一样:使用密钥取决于在地图上的索引为 不良 ,如果您想进行一些过滤和排序.在这种情况下,请使用item.id(如果已经存在id),或者只是为其生成唯一的ID.

The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id if id already there, or just generate unique ids for it.

这篇关于在React中渲染array.map()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆