【发布时间】:2021-04-17 11:57:11
【问题描述】:
我有一个小问题。我为书店市场制作了一个应用程序。现在,每个用户的书都在 Market Screen 上发布。在个人资料屏幕中,数据会更新(姓名、个人资料图像、关于等)。当需要在用户的个人资料屏幕中查看用户的书籍时,问题就出现了。在每个个人资料屏幕上,都会显示当前用户发布的相同书籍。
MarketScreen 代码:
export default function MarketScreen({navigation, route}) {
const [books, setBooks] = useState([]);
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState('');
const [deleted, setDeleted] = useState(false);
const user = firebase.auth().currentUser;
// const userId = firebase.auth().currentUser.uid;
const [userData, setUserData] = useState(null);
const fetchBook = async () => {
try {
const list = [];
await firestore()
.collection('user_book')
.orderBy('postTime', 'desc')
.get()
.then(querySnapshot => {
// console.log('Total books from users', querySnapshot.size);
querySnapshot.forEach(doc => {
const {
userId,
title,
bookImg,
postTime,
author,
genre,
summary,
price,
} = doc.data();
list.push({
id: doc.id,
userId,
title,
bookImg,
postTime: postTime,
author,
genre,
summary,
price,
});
});
});
setBooks(list);
if (loading) {
setLoading(false);
}
console.log('Books', list);
} catch (e) {
console.log(e);
}
};
const getUser = async () => {
const currentUser = await firestore()
.collection('user')
.doc(user.uid)
.get()
.then(documentSnapshot => {
if (documentSnapshot.exists) {
console.log('User Data', documentSnapshot.data());
setUserData(documentSnapshot.data());
}
});
};
useEffect(() => {
getUser();
}, []);
useEffect(() => {
fetchBook();
}, []);
useEffect(() => {
getUser();
fetchBook();
setDeleted(false);
}, [deleted]);
const deleteBook = bookId => {
console.log(bookId);
firestore()
.collection('user_book')
.doc(bookId)
.get()
.then(documentSnapshot => {
if (documentSnapshot.exists) {
const {bookImg} = documentSnapshot.data();
if (bookImg !== null) {
const sotageRef = storage().refFromURL(bookImg);
const imageRef = storage().ref(sotageRef.fullPath);
imageRef
.delete()
.then(() => {
console.log('${bookImg} has been deleted');
deleteFirestoreData(bookId);
setDeleted(true);
})
.catch(e => {
console.log('Error while deleting the image', e);
});
} else {
deleteFirestoreData(bookId);
}
}
});
};
const handleDelete = bookId => {
Alert.alert('Delete Book', 'Are you sure?', [
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{text: 'Confirm', onPress: () => deleteBook(bookId)},
]);
};
const deleteFirestoreData = bookId => {
firestore()
.collection('user_book')
.doc(bookId)
.delete()
.then(() => {
Alert.alert('Your book was deleted from MarketStore');
})
.catch(e => console.log('Error deleting book', e));
};
const ItemSeparatorView = () => {
return (
<View style={{height: 1, width: '100%', backgroundColor: 'black'}}></View>
);
};
return (
<SafeAreaView style={styles.container}>
<FlatList
data={books}
extraData={query}
ItemSeparatorVie={ItemSeparatorView}
keyExtractor={(index, item) => item.toString()}
renderItem={({item}) => (
<TouchableOpacity
style={styles.bookFeed}
onPress={() => navigation.navigate('UserBook', {item})}>
<View style={styles.textViewStyle}>
<Text style={styles.txt1}>
Posted by:
<TouchableOpacity
onPress={() =>
navigation.navigate('Profile', {userId: item.userId})
}>
<Text style={styles.txtUser}>{item.userId}</Text>
</TouchableOpacity>
</Text>
<Text style={styles.txt1}>
Title:
<Text style={styles.txt2}>{item.title}</Text>
</Text>
<Text style={styles.txt1}>
Author:<Text style={styles.txt2}>{item.author}</Text>
</Text>
<Text style={styles.txt1}>
Genre:<Text style={styles.txt2}>{item.genre}</Text>
</Text>
<Text style={styles.txt1}>
Price:<Text>{item.price} lei</Text>
</Text>
<View style={{flexDirection: 'row'}}>
<Text>{moment(item.postTime.toDate()).fromNow()}</Text>
{user.uid === item.userId ? (
<TouchableOpacity
onPress={() => handleDelete(item.id)}
style={{marginLeft: '20%'}}>
<Icon
name="trash"
color={'#DC143C'}
size={30}
style={{marginTop: -10}}
/>
</TouchableOpacity>
) : null}
</View>
</View>
<View style={styles.book}>
{item.bookImg !== null ? (
<Image
style={styles.bookImage}
source={{
uri: item.bookImg,
}}></Image>
) : (
<Text>SFSAFAS</Text>
)}
</View>
</TouchableOpacity>
)}></FlatList>
</SafeAreaView>
);
}
配置文件屏幕代码:
const onLogout = () => {
firebase.auth().signOut();
};
export default function ProfileScreen({navigation, route}) {
const [books, setBooks] = useState([]);
const [loading, setLoading] = useState(true);
const [query, setQuery] = useState('');
const [userData, setUserData] = useState(null);
const [deleted, setDeleted] = useState(false);
const user = firebase.auth().currentUser;
const userIdd = firebase.auth().currentUser.uid;
const fetchBook = async () => {
try {
const list = [];
await firestore()
.collection('user_book')
.where('userId', '==', route.params ? route.params.userId : user.uid)
.orderBy('postTime', 'desc')
.get()
.then(querySnapshot => {
// console.log('Total books from users', querySnapshot.size);
querySnapshot.forEach(doc => {
const {
userId,
title,
bookImg,
postTime,
author,
genre,
summary,
price,
} = doc.data();
list.push({
id: doc.id,
userId,
title,
bookImg,
postTime: postTime,
author,
genre,
summary,
price,
});
});
});
setBooks(list);
if (loading) {
setLoading(false);
}
console.log('Books', list);
} catch (e) {
console.log(e);
}
};
const getUser = async () => {
await firestore()
.collection('user')
.doc(route.params ? route.params.userId : user.uid)
.get()
.then(documentSnapshot => {
if (documentSnapshot.exists) {
console.log('User Data', documentSnapshot.data());
setUserData(documentSnapshot.data());
}
});
};
useEffect(() => {
getUser();
fetchBook();
}, []);
useEffect(() => {
fetchBook();
setDeleted(false);
}, [deleted]);
const deleteBook = bookId => {
console.log(bookId);
firestore()
.collection('user_book')
.doc(bookId)
.get()
.then(documentSnapshot => {
if (documentSnapshot.exists) {
const {bookImg} = documentSnapshot.data();
if (bookImg !== null) {
const sotageRef = storage().refFromURL(bookImg);
const imageRef = storage().ref(sotageRef.fullPath);
imageRef
.delete()
.then(() => {
console.log('${bookImg} has been deleted');
deleteFirestoreData(bookId);
setDeleted(true);
})
.catch(e => {
console.log('Error while deleting the image', e);
});
} else {
deleteFirestoreData(bookId);
}
}
});
};
const handleDelete = bookId => {
Alert.alert('Delete Book', 'Are you sure?', [
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{text: 'Confirm', onPress: () => deleteBook(bookId)},
]);
};
const deleteFirestoreData = bookId => {
firestore()
.collection('user_book')
.doc(bookId)
.delete()
.then(() => {
Alert.alert('Your book was deleted from MarketStore');
})
.catch(e => console.log('Error deleting book', e));
};
const ItemSeparatorView = () => {
return (
<View style={{height: 2, width: '100%', backgroundColor: 'black'}}></View>
);
};
return (
<SafeAreaView style={{flex: 1, backgroundColor: '#fff'}}>
<ScrollView
style={styles.container}
contentContainerStyle={{justifyContent: 'center', alignItems: 'center'}}
showsVerticalScrollIndicator={false}>
<Image
style={styles.userImg}
source={{
uri: userData
? userData.userImg
: 'https://static.remove.bg/remove-bg-web/2a274ebbb5879d870a69caae33d94388a88e0e35/assets/start-0e837dcc57769db2306d8d659f53555feb500b3c5d456879b9c843d1872e7baa.jpg',
}}></Image>
<Text style={styles.userName}>{userData ? userData.name : 'Test'}</Text>
<Text style={styles.userName}>
{/* {route.params ? route.params.userId : userIdd} */}
</Text>
<Text style={styles.aboutUser}>
{userData ? userData.about || 'No details added' : ''}
</Text>
<View style={styles.userBtnWrapper}>
{route.params ? (
<>
<TouchableOpacity style={styles.userBtn} onPress={() => {}}>
<Text style={styles.userBtnTxt}>Message</Text>
</TouchableOpacity>
</>
) : (
<>
<TouchableOpacity
style={styles.userBtn}
onPress={() => navigation.navigate('Messages')}>
<Text style={styles.userBtnTxt}>My messages</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.userBtn}
onPress={() => {
navigation.navigate('EditProfile');
}}>
<Text style={styles.userBtnTxt}>Edit</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.userBtn}
onPress={() => onLogout()}>
<Text style={styles.userBtnTxt}>Logout</Text>
</TouchableOpacity>
</>
)}
</View>
<View style={styles.userInfoWrapper}>
<View style={styles.userInfoItem}>
<Text style={styles.userInfoTitle}></Text>
<Text style={styles.userInfoSubTitle}>{books.length}Books</Text>
</View>
</View>
{books.map(item => (
<TouchableOpacity
style={styles.bookFeed}
onPress={() => navigation.navigate('UserBook', {item})}>
<View style={styles.textViewStyle}>
<Text style={styles.txt1}>
Title:
<Text style={styles.txt2}>{item.title}</Text>
</Text>
<Text style={styles.txt1}>
Author:<Text style={styles.txt2}>{item.author}</Text>
</Text>
<Text style={styles.txt1}>
Genre:<Text style={styles.txt2}>{item.genre}</Text>
</Text>
<Text style={styles.txt1}>
Price:
<Text style={{color: 'black', fontStyle: 'normal'}}>
{item.price} lei
</Text>
</Text>
<View style={{flexDirection: 'row'}}>
<Text>{moment(item.postTime.toDate()).fromNow()}</Text>
{user.uid === item.userId ? (
<TouchableOpacity onPress={() => handleDelete(item.id)}>
<Icon
name="trash"
color={'#DC143C'}
size={30}
style={{marginLeft: '20%'}}
/>
</TouchableOpacity>
) : null}
</View>
</View>
<View style={styles.book}>
{item.bookImg !== null ? (
<Image
style={styles.bookImage}
source={{
uri: item.bookImg,
}}></Image>
) : (
<Text>SFSAFAS</Text>
)}
</View>
</TouchableOpacity>
))}
</ScrollView>
</SafeAreaView>
);
}
【问题讨论】:
标签: javascript firebase react-native google-cloud-firestore fetch