我将在React + Redux + Firebase中向应用程序添加类似功能。单击“赞”(createLike
)可以实时运行,但是deleteLike
不能实时运行。重新加载后,单击“不喜欢”后显示“喜欢”。问题是 deleteDestory在Redux + Firestore中无法异步工作。
代码:
我从Firestore用户定义了currentUser
,并且从参数中提取了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 });
});
};
}
答案 0 :(得分:0)
我完成了。
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;
}
};