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

后端 未结 7 1637
谎友^
谎友^ 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:09

    I think its not correct to give Math.random() for components keys, reason is when you generate random number it is not guaranteed not to get same number again. It is very much possible that same random number is generated again while rendering component, So that time it will fail.

    Some people will argue that if random number range is more it is very less probable that number will not be generated again. Yes correct but you code can generate warning any time.

    One of the quick way is to use new Date() which will be unique.

提交回复
热议问题