【发布时间】:2021-10-09 23:32:03
【问题描述】:
我是 react-native 的新手。我有一个平面列表,它从“状态”中获取数据。这行得通。然后,我添加了一个新函数,以便将新数据添加到平面列表(除了现有数据之外)。
只要我单击“删除”按钮(不要介意名称),平面列表的数据就会被完全删除。我希望输出是这样的
对象 1
对象 2
对象 3(点击按钮后添加)
我做错了什么?能解释一下原因吗?
编辑:我收到此警告,但没有错误。
VirtualizedList:缺少项目的键,请确保指定键或 每个项目的 id 属性或提供自定义 keyExtractor。,
import React, { Component } from "react";
import { Text, View, StyleSheet, Button, FlatList } from "react-native";
class App extends Component {
state = {
counter: 0,
initialElements: [
{ id: "0", text: "Object 1" },
{ id: "1", text: "Object 2" },
],
};
render() {
const currentCounter = this.state.counter;
const exampleState = this.state.initialElements;
const addElement = () => {
let newArray = [...exampleState, { id: "2", text: "Object 3" }];
this.setState({
initialElements: [newArray],
});
};
return (
<View style={styles.container}>
<View style={styles.counter}>
<Text style={styles.textStyle}>{currentCounter}</Text>
</View>
<View style={styles.deleteButton}>
<Button
title="Hello"
onPress={() =>
this.setState({
counter: currentCounter + 1,
})
}
></Button>
<View style={styles.space}></View>
<Button title="Delete" onPress={addElement}></Button>{" "}
{/* as soon as I click here, the content of the list is being deleted */}
</View>
<FlatList
style={styles.listStyle}
key={(item) => item.id}
data={exampleState}
renderItem={(item) => <Text>{item.item.text}</Text>}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: "#fff",
justifyContent: "center",
flex: 1,
flexDirection: "column",
alignItems: "center",
},
counter: {
flexDirection: "row",
justifyContent: "center",
},
deleteButton: {
flexDirection: "row",
margin: 5,
marginTop: 100,
},
space: {
width: 5,
height: 5,
},
textStyle: {
margin: 80,
fontSize: 100,
},
listStyle: {
flexDirection: "column",
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
});
export default App;
【问题讨论】:
标签: react-native