React key值问题

来源:互联网 发布:华驰网络 编辑:程序博客网 时间:2024/05/22 03:14

报错:

Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `List`. See https://fb.me/react-warning-keys for more information.

    in ItemEditor (created by List)
    in List

1.解决方案:http://blog.csdn.net/liuzijiang1123/article/details/66974630;

2.可以设置new Map()对象;


var List = React.createClass({
  getInitialState:function(){
      return{
      key:0,
      list:new Map(),
      editList:new Map()
      }
      },
 
 add:function(){
  const key = ++this.state.key;
  this.state.editList.set(key,{value:''});
  this.forceUpdate();
 },
 
  render:function(){
const listDOM=[];
const editListDOM=[];

for(let item of this.state.list){
listDOM.push(<Item value={item.value} key={item}/>);
}
for(let item of this.state.editList){
editListDOM.push(<ItemEditor value={item.value}  key={item} />);
}
return(
<div>
  <div className="container">
<button className="btn btn-default" onClick={this.add}>Add</button>
<ul className="list-group">
  {listDOM}
  {editListDOM} 
</ul>
</div>
</div>
)
}
})