我有以下组成部分
import {h, Component} from 'preact'
import {getPersons} from '../../lib/datalayer'
import Person from '../person'
import {SearchInput} from '../search'
export default class Persons extends Component {
state = {
allPersons: [],
persons: [],
search: ''
}
async fetchData () {
try {
const allPersons = await getPersons()
this.setState({allPersons: allPersons.slice(), persons: allPersons.slice()})
} catch (error) {
....
}
}
constructor (props) {
super(props)
this.state = {
allPersons: [],
persons: [],
search: ''
}
this.fetchData()
}
onSearchInput = (search) => {
if (search === '') {
this.setState({search: search, persons: this.state.allPersons.slice()})
} else {
const persons = this.state.allPersons.filter(p => p.name.toLowerCase().includes(search.toLowerCase())).slice()
this.setState({search: search, persons: persons)})
}
}
render () {
const {persons} = this.state
return (
<div>
<SearchInput onInputChange={this.onSearchInput} placeHolder={'filter: name'} />
{persons.map(p => <Person person={p} />)}
</div>
)
}
}
该页面呈现“人员”列表,并且顶部具有过滤器。过滤器似乎工作正常,我通过做一个console.log的结果进行了测试
问题是,如果我的列表包含对象:
[{name: 'thomas'}, {name: 'john'}, {name: 'marcus'}, {name: 'usa'}]
然后在搜索输入中输入:“我们”
过滤器工作正常,结果是:
[{name: 'marcus'}, {name: 'usa'}] \\ (the expected result)
在页面中呈现此对象
[{name: 'thomas'}, {name: 'john'}] \\ (wrong, this are the two first elements of the list)
如果我搜索:“ joh”
筛选器的结果是
[{name: 'john'}] \\ (this is fine)
而且页面仅呈现
[{name: 'thomas'}] \\ (the first element in the list)
看起来可以渲染的元素数量还可以,但是列表子元素的内容不会被重新渲染。
我的代码有什么问题?
React使用keys
列表的子项来确定哪些项已更改以及哪些项保持不变。由于您尚未指定key
开机人员,因此它index
成为关键。
当索引为关键时,您可以看到如何将列表缩短为两个项目,如何显示列表中的前两个项目(其他索引现在丢失)。要解决此问题,您必须在此人身上提供唯一的标识符作为键。
从您的对象来看,假设name
是唯一的(通常不是):
{persons.map(p => <Person person={p} key={p.name} />)}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句