删除文档后无法获取实时数据



我将在React+Rredux+Firebase中为应用程序添加类似的功能。当点击"点赞"时(createLike(实时工作,但deleteLike不实时工作。重新加载时,单击"不同"后会显示"类似"。问题是deleteDestory在Redux+Firestore中没有异步工作

代码:我从Firestore用户定义currentUser,从params获取id。用户喜欢每篇文章的内容。

onLike = value => {
const { id, currentUser } = this.props;
if (value) {
this.props.createLike(currentUser.uid, id);
} else {
this.props.deleteLike(currentUser.uid, id);
}
};
renderLike = () => {
const { like } = this.props;
if (like.is_like) {
return (
<button
className="like"
onClick={() => this.onLike(true)}
>
<span>Like</span>
</button>
);
} else {
return (
<button
className="unlike"
onClick={() => this.onLike(false)}
>
<span>Unlike</span>
</button>
);
}
};

Redux代码:

// Fetch like
export function fetchLike(id) {
return dispatch => {
firebase.auth().onAuthStateChanged(user => {
if (user) {
likesRef
.where("uid", "==", user.uid)
.where("cid", "==", id)
.onSnapshot(function(querySnapshot) {
if (querySnapshot) {
querySnapshot.forEach(function(doc) {
dispatch({ type: FETCH_LIKE, payload: doc.data() });
});
}
});
}
});
};
}
// Delete like
export function deleteLike(uid, cid) {
return dispatch => {
likesRef
.where("uid", "==", uid)
.where("cid", "==", cid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
doc.ref.delete();
});
dispatch({ type: DELETE_LIKE });
});
};
}

减速器:

import { FETCH_LIKE } from "../actions";
const initialState = {
is_like: true
};
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_LIKE:
return action.payload;
default:
return state;
}
};

添加

我在这里添加createLike

// Create Like
export function createLike(uid, cid) {
return dispatch => {
likesRef
.add({
uid: uid,
cid: cid,
created_at: firebase.firestore.FieldValue.serverTimestamp()
})
.then(function() {
dispatch({ type: CREATE_LIKE });
});
};
}

我已经完成了。

import { FETCH_LIKE, DELETE_LIKE } from "../actions";
const initialState = {
is_like: true
};
export default (state = initialState, action) => {
switch (action.type) {
case FETCH_LIKE:
return action.payload;
case DELETE_LIKE:
return { is_like: true };
default:
return state;
}
};

最新更新