When giving unique keys to components, is it okay to use Math.random() for generating those keys?

后端 未结 7 1691
谎友^
谎友^ 2020-12-04 23:44

Problem is the following:

I have data in form of a list of a few thousand elements. Some of them are duplicates, and there might be the chance of having duplicate ke

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 00:18

    Just implement the following code in your react component...

    constructor( props ) {
        super( props );
    
        this.keyCount = 0;
        this.getKey = this.getKey.bind(this);
    }
    
    getKey(){
        return this.keyCount++;
    }
    

    ...and call this.getKey() every time you need a new key like:

    key={this.getKey()}
    

提交回复
热议问题