[ PROMPT_NODE_27948 ]
js-hoist-regexp
[ SKILL_DOCUMENTATION ]
## 提升正则表达式的创建
不要在渲染(render)内部创建 RegExp。请将其提升到模块作用域,或使用 `useMemo()` 进行记忆化处理。
**错误示例(每次渲染都会创建新的 RegExp):**
tsx
function Highlighter({ text, query }: Props) {
const regex = new RegExp(`(${query})`, 'gi')
const parts = text.split(regex)
return {parts.map((part, i) => ...)}>
}
**正确示例(记忆化或提升):**
tsx
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` 状态:
typescript
const regex = /foo/g
regex.test('foo') // true, lastIndex = 3
regex.test('foo') // false, lastIndex = 0