React-Native中的FlatList学习记录(三)之keyExtractor值不唯一造成的错误
写作时间:2021/9/22 React-Native版本:0.63.2 目标平台:Android、iOS
开发过程中遇到的一个错误,最后发现是由于数据源有两个item具有相同的key值,代码如下
'use strict';
import React from 'react';
import List from './demos/demo_1/List';
export default class App extends React.Component {
render() {
return (
<List />
);
}
}
'use strict';
import React from 'react';
import { FlatList, Button, SafeAreaView } from 'react-native';
import Item from './Item';
export default class List extends React.Component {
constructor() {
super();
this.state = {
list: [
{ number: '11111111', data: { id: '1', name: 'aaa', age: 11 } },
{ number: '22222222', data: { id: '1', name: 'bbb', age: 22 } },
{ number: '33333333', data: { id: '3', name: 'ccc', age: 33 } },
],
};
}
render() {
return (
<SafeAreaView>
<Button title={'button'} onPress={this.onButtonPress} />
<FlatList data={this.state.list} renderItem={this.renderItem} keyExtractor={this.keyExtractor} />
</SafeAreaView>
);
}
renderItem = ({ item }) => {
return <Item itemData={item} />;
};
keyExtractor = (item) => item.data.id;
onButtonPress = () => {
this.setState({
list: [
{ number: '44444444', data: { id: '4', name: 'ddd', age: 44 } },
{ number: '55555555', data: { id: '5', name: 'eee', age: 55 } },
],
});
};
}
'use strict';
import React from 'react';
import { Text } from 'react-native';
export default class Item extends React.Component {
render() {
return <Text>{this.props.itemData.data.name}</Text>;
}
}
根据代码不难看出,对列表数据进行了替换,希望替换之后的展示数据由3项变为2项,但实际现象如下
点击前
点击后
记录一下,以后开发过程中需要避免出现类似情况
|