如何在React Native中生成唯一ID

16

我是react native的新手,正在使用expo进行第一个项目的开发。我试图为每个用户下的订单生成唯一的ID,以下是我的尝试:

 const orderId = () => {
    var S4 = () => {
      return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (
      S4() +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      "-" +
      S4() +
      S4() +
      S4()
    );
  };
  console.log(orderId);

我在终端上得到的是 [Function orderId]


如果您可以使用库,请尝试这个 -> https://www.npmjs.com/package/react-native-uuid 非常有帮助,易于使用且轻巧。 - poPaTheGuru
1
嘿,谢谢你的回复...我试了一下,它起作用了。谢谢! - RS Motors
1
请检查此链接 https://jsbin.com/kiyunabesu/edit?js,console - Manoj Bhardwaj
你真正的问题在于调用函数引用 orderID 而不是执行函数 orderID()。你只需将最后一行更改为执行该函数,你的算法就会生成 UUID。 - Kelton Temby
6个回答

26

4
今天遇到了这个问题...试图在React Native中使用nanoid,结果就出错了...
既然如此...那为什么不写一个简单的解决方案呢?这个可以很好地完成工作 :)
export function generateUUID(digits) {
    let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVXZ';
    let uuid = [];
    for (let i = 0; i < digits; i++) {
        uuid.push(str[Math.floor(Math.random() * str.length)]);
    }
    return uuid.join('');
}


generateUUID(10) // 7ABLSma6F6
generateUUID(32) // FCGQ91Q5r2y3PkkPFuHhFh9JusMMDFwR


2
function guidGenerator(){
    vary S4 = function(){
        return (((1+Math.random())*0x10000)|0).to String(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

0

2023年02月:Expo SDK 48更新

现在您可以使用expo-crypto生成uuid v4:

import * as Crypto from "expo-crypto";

const UUID = Crypto.randomUUID();

更多信息请参见官方文档


0

回答您的代码问题,而不是建议替代库 -

您唯一遇到的问题是记录函数对象引用orderID而不是执行函数orderID()。这就是为什么控制台输出是[Function orderId]。

您只需更改最后一行以执行该函数,您的算法将生成UUID。

const orderId = () => {

  const S4 = () => {
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  };

  return (
    S4() +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    "-" +
    S4() +
    S4() +
    S4()
  );
}

console.log(orderId());

// output: "87dae617-994c-c506-3a43-da55ec0586e4"

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接