从 2019-04-04 开始,这似乎可以通过 React Hooks' 来完成useState
:
import React, { useState } from 'react'
import uniqueId from 'lodash/utility/uniqueId'
const Field = props => {
const [ id ] = useState(uniqueId('myprefix-'))
return (
<div>
<label htmlFor={id}>{props.label}</label>
<input id={id} type="text"/>
</div>
)
}
export default Field
据我了解,您忽略了数组解构中允许您更新的第二个数组项id
,现在您获得了一个在组件的生命周期内不会再次更新的值。
的值id
将是myprefix-<n>
其中<n>
是从返回增量的整数值uniqueId
。如果这对您来说还不够独特,请考虑制作自己的喜欢
function gen4() {
return Math.random().toString(16).slice(-4)
}
function simpleUniqueId(prefix) {
return (prefix || '').concat([
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4(),
gen4()
].join(''))
}
或查看我在这里发布的库:https : //github.com/rpearce/simple-uniqueid。还有成百上千个其他唯一 ID 的东西,但是uniqueId
带有前缀的lodash应该足以完成工作。
更新 2019-07-10
感谢@Huong Hk 将我指向hooks lazy initial state,总而言之,您可以将一个函数传递给该函数,useState
该函数只能在初始安装上运行。
// before
const [ id ] = useState(uniqueId('myprefix-'))
// after
const [ id ] = useState(() => uniqueId('myprefix-'))