我有一个看起来像这样的组件
import { useState, useEffect, useMemo } from 'react'
import Input from '~/components/Input'
import Fuse from 'fuse.js'
interface Props {
data: any[]
keys: string[]
onUpdate: (data: any[]) => void
placeholder: string
}
const FilterInput = ({ data, keys, onUpdate, placeholder }: Props) => {
const [search, setSearch] = useState('')
const handleSearch = (e) => setSearch(e.target.value)
// Memorize the fuse instance to avoid recreating it on every render
const fuse = useMemo(() => {
return new Fuse(data, {
includeScore: true,
keys,
threshold: 0.3,
distance: 100,
})
}, [data, keys]) //THIS IS THE RELEVANT PART
useEffect(() => {
const results =
search === '' ? data : fuse.search(search).map((result) => result.item)
onUpdate(results) // Invoke onUpdate with the filtered or original list
}, [search, fuse, onUpdate, data]) // Effect dependencies
return (
<div className={'mb-10'}>
<Input value={search} onChange={handleSearch} placeholder={placeholder} />
</div>
)
}
export default FilterInput
我就是这样用的
const ProjectFeatureListing = ({ projects }: Props) => {
const [filteredProjects, setFilteredProjects] = useState(projects) // State to hold the filtered list
console.log(projects)
return (
<div className={'max-w-7xl py-10 mx-auto px-10'}>
<FilterInput
data={projects}
keys={['title', 'description']}
onUpdate={setFilteredProjects}
placeholder={'Find our creators'}
/>
...
我不明白为什么发送这个静态数组会触发重新渲染,因为它没有改变,当我这样做时要清楚
const fuse = useMemo(() => {
return new Fuse(data, {
includeScore: true,
keys,
threshold: 0.3,
distance: 100,
})
}, [data]) //THIS IS THE RELEVANT PART
它不会无限地重新渲染
可能,当
onUpdate
中的 useEffect
更改 ProjectFeatureListing
的状态时,重新渲染会重新创建 ['title', 'description']
对象,并且 FilterInput
会获得对具有相同属性的另一个对象的新引用,这就是回调的原因在 useMemo 中被调用,并且 fuse
变量发生变化,更改后,useEffect
会被 onUpdate
调用,一切都会重新开始。