Javascript 如何在 JS 或 React 中生成 UUID?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/49807952/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate UUIDs in JS or React?
提问by Sam
In my Reactapp, I want to do optimistic updates to create a responsive experience for my users.
在我的React应用程序中,我希望进行乐观更新,为我的用户创建响应式体验。
Having said that I want to send a user entry to my backend with an ID that will be used so that there won't be a different Id for the user's entry next time he/she uses the app. For example, if the user enters a comment, I want to assign its ID with a real UUIDand then send it to my API.
话虽如此,我想将一个用户条目发送到我的后端,并带有一个将被使用的 ID,以便用户下次使用该应用程序时不会有不同的 ID。例如,如果用户输入评论,我想为其分配一个真实的 ID,UUID然后将其发送到我的 API。
I understand JavaScriptor Reactdon't really have a built-in way to generate UUID/GUIDvalues. I've seen many articles that produce randomized values that look like UUID/GUID's but they really are not and I don't want to use them as ID's for user entries.
我理解JavaScript或React没有真正的内置方式来生成UUID/GUID值。我看过很多文章,它们产生看起来像UUID/GUID的随机值,但它们确实不是,我不想将它们用作用户条目的 ID。
How do I get real UUID/GUIDvalues in my frontend? Do I call my backend API to get them? I can create an endpoint in my API that spits out 10 or 20 GUID's at a time and I can store them for future use in my frontend but this sounds a bit absurd.
如何在我的前端获得真实UUID/GUID值?我是否调用我的后端 API 来获取它们?我可以在我的 API 中创建一个端点,一次吐出 10 或 20GUID个,我可以将它们存储起来以备将来在我的前端使用,但这听起来有点荒谬。
I don't want to reinvent the wheel here as I'm not the first person to face this scenario. How do I get real UUIDvalues on my frontend?
我不想在这里重新发明轮子,因为我不是第一个遇到这种情况的人。我如何UUID在我的前端获得真正的价值?
采纳答案by markau
You can use the uuid npm package. You probably want to use a v4 UUID. (Previous UUID versions use things like a timestamp or network card MAC address as seeds to the random generator).
您可以使用uuid npm 包。您可能想要使用 v4 UUID。(以前的 UUID 版本使用诸如时间戳或网卡 MAC 地址之类的东西作为随机生成器的种子)。
回答by Dan Wilkerson
You're probably just fine generating them client-side - it takes many, many UUIDs before you even approach a 1 in a million rate of collision (citing the answer below).
您可能在客户端生成它们很好 - 在您甚至接近百万分之一的碰撞率之前需要很多很多 UUID(引用下面的答案)。
This answer has several solutions to generating them client-side in a way that complies with RFC4122:
这个答案有几种解决方案,以符合RFC4122的方式在客户端生成它们:
Create GUID / UUID in JavaScript?
Alternatively, you could generate temporary optimistic IDs and then replace them when you get a response from the server.
或者,您可以生成临时的乐观 ID,然后在收到服务器响应时替换它们。

