【发布时间】:2021-12-07 13:38:18
【问题描述】:
我在我的 react 应用中添加了喜欢和不喜欢的按钮。我正在使用 redux 来管理状态并将数据存储在 firebase 实时数据库中。按钮正常工作,但我需要重新加载页面以显示帖子已被喜欢/不喜欢,它不会自行重新呈现。我尝试同时使用 forceUpdate 和 setState,但都不起作用。
postLiked = (id) => {
this.props.onLikePost(this.props.user, id)
this.forceUpdate()
}
postUnliked = (id, unlikeID) => {
this.props.onUnlikePost(id, unlikeID)
}
render() {
{this.props.data.map((res) => {
const liked = [];
for(let key in res.LikedBy){
liked.push({
...res.LikedBy[key],
id: key
});
}
let boolButton = false;
if(liked.filter((val) => {
if(val.username === this.props.user) {
boolButton = true
}
}))
return(
<div>
<div className="bottomButtons">
{boolButton ? <Button className="btn btn-primary likeDislike"
id="likeButton"
onClick={() => this.postUnliked(res.id, liked.find((val) => {
if(val.username === this.props.user){
return val.id;
}
}))}
>
<FontAwesomeIcon icon={faThumbsUp} style={{width:"13.5px", color:"white"}}/>
</Button> : <Button className="btn btn-light likeDislike"
id="likeButton"
onClick={() => this.postLiked(res.id)}
>
<FontAwesomeIcon icon={faThumbsUp} style={{width:"13.5px"}}/>
</Button>
}
这些是动作函数
export const likePost = (username, postId) => {
const req = {
username,
postId
}
return (dispatch) => {
axios.post('/Data/' + postId + '/LikedBy.json', req)
.then((res) => {
dispatch({
type: actionTypes.Like_Post,
payload: res
})
})
}
}
export const unlikePost = (id, unlikeId) => {
return (dispatch) => {
axios.delete('/Data/' + id + '/LikedBy/' + unlikeId.id + '.json')
.then((res) => {
dispatch({
type: actionTypes.Unlike_Post
})
}).catch((error) => {
console.log(error)
})
}
}
这是reducer函数
const initialState = {
Data: []
}
const reducer = (state = initialState, action) => {
switch(action.type){
case actionTypes.Like_Post:
return {
...state,
Data: state.Data.map((post) => post.id === action.payload.postId
? {...post, LikedBy: post.LikedBy.concat(action.payload.username)}:post),
loading: false,
}
case actionTypes.Unlike_Post:
return {
...state,
Data: state.Data,
loading: false,
}
编辑
我尝试了其他方法,但没有任何效果。问题出在减速器上,我没有正确更新状态。我尝试更新 LikedBy 字段,但只收到错误消息。
尝试了这种方法,但我得到一个错误,说 res.map 不是函数
case actionTypes.Like_Post:
return {
...state,
Data: state.Data.forEach((res) => res.map((q) => {
if(q.id === action.payload.postId) {
q.LikedBy.concat(action.payload.username)
}
return q
})
)
}
【问题讨论】:
标签: javascript reactjs react-redux