我正在用Redux和Firebase/Firestore构建一个React原生社交媒体应用程序,我需要实现一个Following屏幕,其中用户可以实时看到他在关注谁。
我已经设法完成了,让一切都工作,除了删除部分。当一个用户在redux存储中被添加到以下列表中,然后被删除时,他不会被删除。
我让它工作的方式如下:firestore集合上的一个监听器,每当一个用户被关注/取消关注时,他将成功地从后面的中添加/删除。状态。然后,我在Redux中有一个操作,从跟随中获取每个id,并将该用户的所有数据收集到另一个状态followwedusers(在following状态下,他只获取用户的id,并使用该id从用户集合中获取数据,然后将这些数据分派到followwedusers状态)。下面是动作
export const followingState = () => {
return((dispatch) => {
firebase
.firestore()
.collection("following")
.doc(firebase.auth().currentUser.uid)
.collection("userFollowing")
.onSnapshot((snapshot) => {
let following = snapshot.docs.map(doc => {
return doc.id;
})
dispatch({type : FOLLOWING_STATE, following });
for(let j = 0; j < following.length; j++){
dispatch(followedUsersState(following[j]));
};
})
});
};
export const followedUsersState = (uid) => {
return((dispatch) => {
firebase
.firestore()
.collection("allUsers")
.doc(uid)
.get()
.then((snapshot) => {
let user = {snapshot.id, ...snapshot.data()};
dispatch({type : USERS_FOLLOWED_STATE, user});
});
})
}
还原剂也:
case FOLLOWING_STATE:
return {
...state,
following: action.following
};
case FOLLOWED_USERS_STATE:
return {
...state,
followedUsers: [...state.followedUsers, action.user]
};
我认为问题出在你的"followwed_users_state"action reducer,通过调用followedUsers:[...state.followedUsers,action.user]
,你保持followedUsers
的旧状态,并在每次.collection("userFollowing").onSnapshot(...)
火灾时添加新用户,我认为你应该尝试一次调度users_followwed_state与用户数组,这样你就刷新了整个数组,我希望这能帮助
export const followingState = () => {
return((dispatch) => {
firebase
.firestore()
.collection("following")
.doc(firebase.auth().currentUser.uid)
.collection("userFollowing")
.onSnapshot((snapshot) => {
let following = snapshot.docs.map(doc => {
return doc.id;
})
dispatch({type : FOLLOWING_STATE, following });
// get all users data from db in one go
const proms = following.map((id)=>{
return getFollowedUserState(id)
})
Promise.all(proms).then((snapshots)=>{
const users = snapshots.map((snapshot)=>{
return {id:snapshot.id, ...snapshot.data()};
})
// set all users data to local state in one go
dispatch({type : USERS_FOLLOWED_STATE, users});
})
})
});
};
const getFollowedUserState = (uid)=>{
return firebase
.firestore()
.collection("allUsers")
.doc(uid)
.get()
}
case FOLLOWING_STATE:
return {
...state,
following: action.following
};
case FOLLOWED_USERS_STATE:
return {
...state,
followedUsers: action.users
};