git地址:https://github.com/ai/nanoid/
安装
npm i nanoid -S
引入
import { nanoid } from ‘nanoid’
1.请勿将nanoid用于key。在React中key渲染之间应该保持一致。这是错误的代码:
2.正确的做法。this.id将仅生成一次:
id = nanoid()
render () {
return
}
3.如果要使用Nano ID作为id,则必须设置一些字符串前缀。Nano ID可以从数字开始。HTML ID不能从数字开头。
注意
此插件使用了 Uint8Array 对象,对应浏览器兼容性,如果要支持 chrome 和 ie 低版本,请使用下面方法生成uuid
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | Android webview | Chrome for Android | Firefox for Android | Opera for Android | Safari on iOS | Samsung Internet | Node.js | |
Uint8Array |
Full support7 | Full support12 | Full support4 | Full support10 | Full support11.6 | Full support5.1 | Full support4 | Full support18 | Full support4 | Full support12 | Full support4.2 | Full support1.0 | Full support0.10 |
Uint8Array() constructor |
Full support7 | Full support12 | Full support4 | Full support10 | Full support11.6 | Full support5.1 | Full support4 | Full support18 | Full support4 | Full support12 | Full support4.2 | Full support1.0 | Full support0.10 |
生成 uuid 方法
参考:js如何生成唯一标识符UUID_FreeSpider-CSDN博客
function generateUUID() {
var d = new Date().getTime();
if (window.performance && typeof window.performance.now === "function") {
d += performance.now(); //use high-precision timer if available
}
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16);
});
return uuid;
}