[英]How do I pass a specific object from a FlatList to a function so I could delete it from Firestore?
I have a watchlist of bookings for movies and when I click on a button for one of the FlatList rendered components I'd like to pass the object to the delete function and then to remove it from Firestore.我有一个电影预订观察列表,当我单击 FlatList 渲染组件之一的按钮时,我想将 object 传递给删除 function,然后将其从 Firestore 中删除。 I'm kind of stuck on how to do this.
我有点不知道如何做到这一点。 This is what I have so far:
这是我到目前为止所拥有的:
const WatchList = () => {
const uid = auth.currentUser.uid;
const docRef = doc(db, 'users', uid);
const [user, setUser] = useState({});
const [watched, setWatched] = useState(true);
const [text, setText] = useState('Watched movies');
const [filteredBookings, setFilteredBookings] = useState(bookings);
const bookingsRef = collection(db, "booking");
const [bookings, setBookings] = useState({});
useEffect(() => {
getUser();
getBookings();
},[])
const getUser = async () => {
const snap = await getDoc(docRef)
setUser({user, ...snap.data()})
}
const getBookings = async () => {
const q = query(bookingsRef, where("users","array-contains",auth.currentUser.uid));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
const a = [];
querySnapshot.forEach((doc) => {
a.push(doc.data());
});
setBookings(querySnapshot.docs);
});
}
const deleteBooking = (item) => {
console.log(item.data.().title)
}
return (
<View>
<View>
<Text>{text}</Text>
</View>
<FlatList
data = {filteredBookings}
numColumns = {1}
renderItem = {({item}) => (
<View>
<View>
<Text>{item.data().movie}</Text>
<Text>{item.data().day} - {item.data().showtime}</Text>
</View>
<View>
<TouchableOpacity onPress = {() => {deleteBooking(item)}}>
<Text>Delete</Text>
</TouchableOpacity>
</View>
</View>
)}
/>
</View>
)
}
export default WatchList`
I've been trying to pass an item to display it in the console log to see if I got the right one first, but it's not working, so I'd really appreaciate some pointers.我一直在尝试传递一个项目以将其显示在控制台日志中,以查看我是否首先获得了正确的项目,但它不起作用,所以我真的很感激一些指示。 Thank you!
谢谢!
In your delete button's onPress method which you have defined as deleteBooking() you will get index also.在您定义为 deleteBooking() 的删除按钮的 onPress 方法中,您也会获得索引。 you can rewrite as deleteBooking(item,index).
您可以重写为 deleteBooking(item,index)。 and now in your definition use splice method of array.
现在在您的定义中使用数组的拼接方法。 eg arrayName.splice(index,1) this will delete the record of given index.
例如arrayName.splice(index,1)这将删除给定索引的记录。 For your array it should be like bookings.splice(index,1) .
对于您的数组,它应该类似于bookings.splice(index,1) 。 Here 1 represents how many record you want to delete from given index.
这里 1 表示要从给定索引中删除多少条记录。
Let me know doest it works for you or not.让我知道它是否适合你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.