我正在尝试在更改输入“过滤器”时过滤此数组,但是当我尝试键入它时,过滤器过滤得很好,但会覆盖原始列表。那么如何在键入时过滤列表并在擦除过滤值时返回到原始列表?
const [persons, setPersons] = useState([
{ name: 'Arto Hellas', number: '040-123456' },
{ name: 'Ada Lovelace', number: '39-44-5323523' },
{ name: 'Dan Abramov', number: '12-43-234345' },
{ name: 'Mary Poppendieck', number: '39-23-6423122' }
])
const [filter, setFilter] = useState('')
const handleFilter = e => {
setFilter(e.target.value)
const personsFiltered = persons.filter(({ name }) => name.includes(filter))
if (personsFiltered.length > 0)
setPersons(personsFiltered)
}
return (
<div>
<input value={filter} onChange={handleFilter} />
{persons.map((person, index) => <p key={index}>{person.name} {person.number}</p>)}
</div>
)
答案 0 :(得分:1)
您必须为过滤后的值保留其他状态。
只需使用另一个useState
const [persons, setPersons] = useState([
{ name: 'Arto Hellas', number: '040-123456' },
{ name: 'Ada Lovelace', number: '39-44-5323523' },
{ name: 'Dan Abramov', number: '12-43-234345' },
{ name: 'Mary Poppendieck', number: '39-23-6423122' }
])
// use additional state here
const [personsFiltered, setPersonsFiltered] = useState(persons);
const [filter, setFilter] = useState('')
const handleFilter = e => {
setFilter(e.target.value)
const personsFiltered = persons.filter(({ name }) => name.includes(filter))
if (personsFiltered.length > 0)
// set the additional state here
setPersonsFiltered(personsFiltered)
}
return(<input value={filter} onChange={handleFilter} />)
答案 1 :(得分:1)
通过将结果作为渲染的一部分进行过滤,您应该能够实现所需的目标。您正在更新filter
状态,因此重新渲染应在事件发生时按预期触发:
编辑:我看到您已使用渲染代码更新了问题。您应该可以仅将filter
函数应用于已经拥有的函数:
{persons.filter(({ name }) => name.includes(filter)).map((person, index) => <p key={index}>{person.name} {person.number}</p>)}