name: js-hoist-regexp description: 在渲染之外提升RegExp创建或使用useMemo()进行记忆化。适用于在React组件或频繁调用的函数中使用正则表达式时。
提升RegExp创建
不要在渲染内部创建RegExp。提升到模块作用域或使用useMemo()进行记忆化。
不正确(每次渲染都新建RegExp):
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
正确(记忆化或提升):
const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
function Highlighter({ text, query }: Props) {
const regex = useMemo(
() => new RegExp(`(${escapeRegex(query)})`, 'gi'),
[query]
)
const parts = text.split(regex)
return <>{parts.map((part, i) => ...)}</>
}
警告(全局正则表达式有可变状态):
全局正则表达式(/g)有可变的lastIndex状态:
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0