ReactJS键未显示

时间:2017-12-21 16:40:23

标签: javascript reactjs

尝试使用ReactJS生成表,并且在此表中我希望有一个唯一的键来标识每一行(如ReactJS所推荐的)。以下代码运行并生成我想要的表,除了以下错误:

Warning: 'Each child in an array or iterator should have a unique "key" prop' 

查看我生成的HTML'键'确实不存在领域。我也尝试过key = {index},但它不起作用

export class Tablecontent extends Component{

  constructor(props){
    super(props);
    this.state={
      fileinfo:'null'
    }
  }
  render(){
    //const fileinfo = this.props.rows;
    const fileinfo = ['myFile1.doc','myFile2.doc'];
    var row='';
    console.log("FILEINFO:"+fileinfo);
    if(fileinfo=='null')
    {
       row ='';
    }
    else {

     row = fileinfo.map((data,index) =>
    <tr>
      <td key="filename_{index}">{data}</td>
      <td key="date_{index}">2/12/2017</td>
      <td key="size_{index}">2.1 MB</td>
    </tr>
    );
  }
    return(
      <div>
        <table>
        <tbody>
          <tr>
            <th>Name</th>
            <th>Date Created</th>
            <th>Size</th>
          </tr>{row}</tbody>
    </table>
      </div>
    );

  }
}

结果HTML:

<table>
    <tbody>
    <tr><th>Name</th><th>Date Created</th><th>Size</th></tr>
     <tr><td>myFile1.doc</td><td>2/12/2017</td><td>2.1 MB</td></tr>
    <tr><td>myFile2.doc</td><td>2/12/2017</td><td>2.1 MB</td>
    </tr>
    </tbody>
</table>

1 个答案:

答案 0 :(得分:4)

它希望在map函数中返回外部元素上的键,如下所示。关键是React的内部使用,并且不会在html中显示。

 row = fileinfo.map((data,index) =>
    <tr key={index}>
      <td key="filename_{index}">{data}</td>
      <td key="date_{index}">2/12/2017</td>
      <td key="size_{index}">2.1 MB</td>
    </tr>
    );