React native 为什么在我的React原生平面列表上有相同值的键?
我并不总是收到关于具有相同值的键的警告,但它经常出现。大多数情况下,它发生在第一次搜索时 这是我的密码:React native 为什么在我的React原生平面列表上有相同值的键?,react-native,react-native-flatlist,React Native,React Native Flatlist,我并不总是收到关于具有相同值的键的警告,但它经常出现。大多数情况下,它发生在第一次搜索时 这是我的密码: const ITEMS_PER_PAGE = 5 export default class SearchForm extends Component { state = { allStates: [], states: [], page: 1, displayStatesList: false, }
const ITEMS_PER_PAGE = 5
export default class SearchForm extends Component {
state = {
allStates: [],
states: [],
page: 1,
displayStatesList: false,
}
componentDidMount = async () => {
await fetch('https://servicodados.ibge.gov.br/api/v1/localidades/estados', {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
})
.then(res => res.json())
.then(res => this.setState({ allStates: res, states: res.slice(0, ITEMS_PER_PAGE -1) }))
}
updateSearch = search => {
let { allStates } = this.state
this.setState({
states: allStates.filter(res => res.nome.includes(search)),
displayStatesList: true,
search: search,
})
}
loadMore = () => {
const { page, states, allStates, search } = this.state
const start = page*ITEMS_PER_PAGE
const end = (page+1)*ITEMS_PER_PAGE-1
const newData = allStates.slice(start, end).filter(res => res.nome.includes(search))
console.log(allStates.length)
this.setState({
states: [...states, ...newData],
page: page + 1,
})
}
selectItem = (nome) => {
console.log('press', nome)
this.setState({
search: nome,
displayStatesList: false,
})
}
renderItem = ({ item }) => {
return (
<View>
<ListItem
title={item.nome}
onPress={() => this.selectItem(item.nome)}
/>
</View>
);
}
render() {
const {
search,
states,
displayStatesList,
} = this.state
return (
<View style={styles.container}>
<SearchBar
placeholder="Type Here..."
onChangeText={this.updateSearch}
value={search}
lightTheme
/>
<View style={styles.listContainer}>
{displayStatesList && <FlatList
data={states}
keyExtractor={item => item.id.toString()}
renderItem={this.renderItem}
onEndReached={this.loadMore}
onEndReachedThreshold={0.7}
/>}
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignSelf: 'stretch',
backgroundColor: '#fff',
},
listContainer: {
height: 200
},
})
也许我正在做一些不被推荐的事情,这是导致错误的原因?
或者可能。切片不正确
观察:如果API不工作,我可以放置一个json文件进行测试。尝试使用以确保对象数组中没有重复项。可能是API响应中存在重复项,或者在loadMore方法中添加新数据时来自您这边 您可以尝试更改此keyExtractor={item,index=>index.toString} 并将其作为prop添加到renderItem key={index}的第一个组件中
这将确保为“Flatlist”中的每个项目提供的键是唯一的。这可以解决警告,但不能解决我有重复值这一事实。在此之前请尝试console.log in loadMore方法。设置状态对于状态和新数据,请检查是否有重复。404:-未找到