我试图根据 ID 从 fire store 中逐一删除文档,但代码无法按预期工作。
const Charities = () => {
const [userData, setUserData] = useState([]);
{/*fetch all Documents Donation from database*/}
const fetchData = async () => {
const querySnapshot = await getDocs(collection(db, "Charities"));
const data = [];
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
data.push(doc.data());
});
setUserData(data);
};
useEffect(()=>{
fetchData()
},[])
{/*Delete document donation function*/}
const deleteDocById = async(id)=>{
try {
await deleteDoc(doc(db, "Charities", id))
console.log('The document is deleted successfully')
} catch (error) {
console.log(error)
}
}
function renderBody(){
return(
<View>
{userData.map((item)=>(
<TouchableOpacity onPress={()=>deleteDocById(item.id)}>
<View style={style.card} >
<Text style={{
fontWeight:'600',
color:COLORS.red
}}>Delete</Text>
</View>
</TouchableOpacity>
)
)}
我无法弄清楚,我确实相信问题出在 id 上,代码根本无法单独删除每个文档,非常感谢任何帮助
尝试下面,写了一个模拟代码。让我知道它是否有效 -
import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { getDocs, collection, deleteDoc, doc } from 'firebase/firestore';
import { db } from './firebase'; // Adjust this import based on your project structure
const Charities = () => {
const [userData, setUserData] = useState([]);
// Fetch all Documents Donation from database
const fetchData = async () => {
const querySnapshot = await getDocs(collection(db, "Charities"));
const data = [];
querySnapshot.forEach((doc) => {
console.log(doc.id, " => ", doc.data());
data.push({ id: doc.id, ...doc.data() });
});
setUserData(data);
};
useEffect(() => {
fetchData();
}, []);
// Delete document donation function
const deleteDocById = async (id) => {
try {
await deleteDoc(doc(db, "Charities", id));
console.log('The document is deleted successfully');
// Fetch data again to update the list
fetchData();
} catch (error) {
console.log(error);
}
};
const renderBody = () => {
return (
<View>
{userData.map((item) => (
<TouchableOpacity key={item.id} onPress={() => deleteDocById(item.id)}>
<View style={styles.card}>
<Text style={styles.deleteText}>Delete</Text>
</View>
</TouchableOpacity>
))}
</View>
);
};
return (
<View>
{renderBody()}
</View>
);
};
const styles = StyleSheet.create({
card: {
padding: 10,
margin: 10,
backgroundColor: '#f8f8f8',
borderRadius: 5,
},
deleteText: {
fontWeight: '600',
color: 'red',
},
});
export default Charities;