【问题标题】:React: unique ID generationReact:唯一 ID 生成
【发布时间】:2020-11-25 22:56:53
【问题描述】:

谁能建议我如何在 React 中创建一个 ID 生成函数?

到目前为止,我已经尝试通过一个 uuid npm 包 https://www.npmjs.com/package/uuid 来解决这个问题,

import uuidv4 from 'uuid'

    helpIdGenerator {
        const uuidv4 = require('uuid/v4')
    }

但它似乎不起作用。

【问题讨论】:

  • 在这种情况下“不起作用”是什么意思?你有没有得到一个错误,你没有得到任何输出,还是别的什么?
  • 你试过lodash.uniqueid吗?
  • 分配后return uuidv4()
  • @HardikModha 是的,但我该如何放入函数中?

标签: reactjs react-native uuid


【解决方案1】:

这个功能可能有用:

function guidGenerator() {
    var S4 = function() {
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
    };
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());
}

这会生成像这样的随机 id:

6b33fce8-1745-f8de-4ad8-4ee42585oprf

【讨论】:

  • 这很棒。谢谢楼主
【解决方案2】:

这对我有用:

import uuid from 'react-native-uuid'

let id = uuid.v1()

【讨论】:

    【解决方案3】:

    (代表问题作者发布解决方案)

    通过使用修复:

    helpIdGenerator = () => {
    
        const uuidv4 = require('uuid/v4')
    
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-22
      • 1970-01-01
      • 2015-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-04
      • 2011-06-20
      相关资源
      最近更新 更多