为从表单中获取的值生成唯一Id的最简单方法(React)



我试图从输入中获取值,为其分配一个唯一的id,然后将名称和id传递给addFolder((函数。然后,该对象将被推到该州文件夹数组的末尾。我的主要问题是试图创建一个唯一的id

state = {
name: '',
id: ''
}
static contextType = Context;
handleChange = (e) => {
this.setState({name: e.target.value, id: ?? })  <-----------
}
handleSubmit = (e) => {
e.preventDefault();
this.context.addFolder(this.state.name, this.state.id)
}
render() {
return (
<div>
<form 
className='AddFolderForm'
onSubmit={this.handleSubmit}
>
<h2>Add Folder</h2>
<label >Name: </label>
<input 
type="text"
id=??            <------------------
placeholder="Folder Name"
value={this.state.name}
onChange={this.handleChange}
/>
<button
type="submit"
>Submit
</button>
</form>
</div>
)
}
}

export default AddFolder
class App extends Component {
state = {
notes: [],
folders: [],
};
.... other code...
addFolder = (name, id) => {
this.setState(prevState => ({
folders: [...prevState.folders, {
"name": `${name}`,
"id": `${id}`,
}]
}))
}

您应该检查此库的uuid以获取react,从而生成唯一的id。你有5个版本来生成它。

npm install uuid --save

import { v1 as uuidv1 } from 'uuid';
//This is your unique id
const id = uuidv1();

在Vanilla js中有一个简单的方法。如果你使用这种方法,你就不需要添加任何依赖项来提高你的项目性能。

let uniqueId = (function () {
let num = 0;
return function (prefix) {
prefix = String(prefix) || '';
num += 1;
return prefix + num;
}
}
());
let id = uniqueId('id_');
console.log(id); // 'id_1'

lodash还有另一种方法。使用以下命令添加lodash

npm i --save lodash

然后像下面的例子一样使用

let _ = require('lodash');
let id = _.uniqueId('id_');
console.log(id); // 'id_1'
let i = 10, ids = [];
while (i--) {
ids.push(_.uniqueId('id_'));
}
console.log(ids[0]); // id_2
console.log(ids[9]); // id_11

如果您需要不同格式的Id,请按照以下方式操作。它也是一个高级的Vanilla js解决方案。

let uniqueId = (function () {
let c = 0,
st = new Date();
return function (prefix) {
var t = new Date() - st,
r = Math.floor(Math.random() * 1000),
str;
prefix = String(prefix) || '';
str = '-' + c + '-' + t + '-' + r;
c += 1;
return prefix + str;
}
}
());
console.log(uniqueId('id'));
console.log(uniqueId('id'));
console.log(uniqueId('id'));
setTimeout(function () {
console.log(uniqueId('id'));
}, 1000);
/*
id-0-1-145
id-1-8-113
id-2-9-598
id-3-1018-910
*/

最新更新