javascript - 为什么我的所有文档都应该被删除,而它只应该执行和删除一个特定的文档?
问题描述
当我在 React Native 中进入这个屏幕时,我的所有文档都被删除了。如何获取代码以删除 doc.id 为key
in的文档deleteTodo()
。我认为 deleteTodo 只会在TouchableOpacity
被按下时执行,但是当我进入屏幕时它会被执行。
useEffect(() => {
firebase
.firestore()
.collection('users')
.doc(uid)
.collection('tasks')
.get()
.then((snapshot) => {
const docList = []
snapshot.forEach((doc) => {
docList.push({
key: doc.id,
task: doc.data().task,
completed: doc.data().completed,
});
})
setList(docList);
})
.catch((error) => {
console.log(error)
})
}, [])
function deleteTodo(key) {
var uid = firebase.auth().currentUser.uid;
firebase.firestore().collection('users').doc(uid).collection('tasks').doc(key).delete().then(() => {
console.log("Successfully deleted document!")
}).catch(error => console.log(error));
}
swipeRight = (key) => {
return(
<View style={styles.rightAction}>
<TouchableOpacity onPress={deleteTodo(key)}>
<Icon name="trash" size={28} color={"red"} />
</TouchableOpacity>
</View>
)
}
return (
<View style={styles.container}>
<Text style={styles.title}>Here is your tasks for today</Text>
<View style={styles.taskList}>
<FlatList style={{width: '100%'}}
data={list}
keyExtractor={(item) => item.key}
renderItem={({item}) => {
return(
<Swipeable renderRightActions={() => swipeRight(item.key)}>
<TouchableOpacity style={styles.task} onPress={() => console.log("This button got pressed")}>
<Text style={{margin: 15, textDecorationLine: item.completed ? 'line-through' : 'none'}}>{item.task}</Text>
</TouchableOpacity>
</Swipeable>
)
}}
/>
</View>
<View style={styles.taskcreation}>
<TextInput
style={styles.inputBox}
value={task}
onChangeText={(task) => setTask(task)}
placeholder='What do you want to do?'
/>
<TouchableOpacity style={styles.button} onPress={handleTaskCreation}>
<Text style={styles.buttonText}>Create task</Text>
</TouchableOpacity>
</View>
</View>
)
}
解决方案
由于您在平面列表中并在渲染中使用项目,因此将“键”更改为“项目”,如下所示:
const deleteTodo = (item) => {
const uid = firebase.auth().currentUser.uid;
firebase
.firestore()
.collection('users')
.doc(uid)
.collection('tasks')
.doc(item.key)
.delete()
.then(() => {
console.log("Successfully deleted document!")
})
.catch(error => console.log(error));
}
const swipeRight = (item) => {
return (
<RectButton onPress={() => deleteTodo(item)}>
<Icon name="trash" size={28} color={"red"} />
</RectButton>
);
};
对于可刷卡
<Swipeable renderRightActions={() => swipeRight(item)}>
<Text style={{margin: 15,
textDecorationLine: item.completed ? 'line-
through' : 'none'}}>
{item.task}
</Text>
</Swipeable>
推荐阅读
- c# - 在服务器上存储数据并在加载时使用 c#
- php - 如果不存在则自动创建表导致错误
- laravel - Laravel 5.6 .env 值解析为(未知)
- serialization - Arduino - 读取串行数据
- c# - 替换文件夹名称不起作用
- configuration - 要求未使用汇总定义
- angular - Angular 6 反应式表单验证不起作用
- docker - 在 Gitlab CI 上调试失败的 Docker 构建并执行中间层
- google-cloud-storage - GCP:如何通过 Google 的 Python API 客户端实现“gcloud alpha firestore export ...”shell 命令
- jquery - 如果值大于 X,则在 keyup 上做某事