为每个帖子提供唯一的ID

时间:2018-12-18 15:46:34

标签: reactjs next.js

大家好,我的网站上有一些静态内容,要制作一些动态内容,所以我有5条不同的新闻,并想给他们提供唯一的ID,例如,当您继续阅读时,您必须获得

id:2 title: President-Elections

所以我尝试制作一些数组

const posts = [
 {id: 1, title: "some title", content: "some content"},
 {id: 2, title: "some title2", content: "some content2"},
 {id: 3, title: "some title3", content: "some content3"},
 {id: 4, title: "some title4", content: "some content4"},
 {id: 4, title: "some title5", content: "some content5"},
];

现在我想赋予每个帖子唯一的ID,但不知道如何做。

2 个答案:

答案 0 :(得分:2)

您可以使用uuid生成器。 https://www.npmjs.com/package/uuid

答案 1 :(得分:0)

function generateUUID() { // Public Domain/MIT
    var d = new Date().getTime();
    if (typeof performance !== 'undefined' && typeof performance.now === 'function'){
        d += performance.now(); //use high-precision timer if available
    }
    return '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);
    });
}