如果帖子ID等于action.payload,则增加点赞计数

时间:2018-10-18 14:24:29

标签: javascript reactjs redux react-redux

我正在开发一个社交网络应用,我想切换特定帖子的点击次数(它应该在第一次点击时增加1,并且在再次按下时应返回null)。但是现在当我单击“赞”按钮时,什么也没有发生,并且屏幕消失了。我无法弄清楚我的代码有什么问题。

这是我的文件->动作创建者

export const fetchPosts = () => async dispatch => {
  const request = await axios.get(`${ROOT_URL}/post`, {
    headers: { Authorization: `${token}` }
  });
  dispatch({
    type: FETCH_POSTS,
    payload: request
  });
};



export const incrementLikesCount = id => {
  return {
    type: INCREMENT_LIKES_COUNT,
    payload: id
  };
};

index.js(reducer)

import auth from "./authReducer";
import user from "./userReducer";
import post from "./postReducer";

export default combineReducers({
  auth,
  user,
  post,
  form: formReducer
});

postreducer.js

import _ from "lodash";
import { FETCH_POSTS, INCREMENT_LIKES_COUNT } from "../actions/types";

const initialState = {
  postDetail: "",
  likesCount: null
};

const post = (state = initialState, action) => {
  switch (action.type) {
    case FETCH_POSTS:
      return {
        ...state,
        postDetail: _.mapKeys(action.payload.data.data, "_id")
      };

    case INCREMENT_LIKES_COUNT:
      return _.values(state.postDetail)
        .reverse()
        .map(post => {
          if (action.payload === post._id) {
            if (state.likesCount === null) {
              console.log("I got executed");
              return { ...state, likesCount: state.likesCount + 1 };
            } else {
              return {
                ...state,
                likesCount: null
              };
            }
          } else {
            return {
              state
            };
          }
        });

    default:
      return state;
  }
};

export default post;

和我的反应组件

import _ from "lodash";
// import uuid from "uuid";
import { connect } from "react-redux";
import React, { Component } from "react";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {
  faHeart,
  faCommentAlt,
  faShareAlt
} from "@fortawesome/free-solid-svg-icons";

import { fetchPosts, incrementLikesCount } from "../../../actions/FeedPost";
import "./FeedPosts.css";

class FeedPosts extends Component {
  componentDidMount() {
    if (!this.props.fetchPosts) {
      return <div>Loading...</div>;
    }
    this.props.fetchPosts();
  }

  renderPosts = () => {
    return _.values(this.props.post)
      .reverse()
      .map(post => (
        <div key={post._id} className="post-content">
          <img
            src={require("../../../img/blue.jpeg")}
            alt="user"
            className="user-image"
          />
          <span>{post.postBy}</span>
          <span>{post.userDesignation}</span>
          <li>{post.postText}</li>
          <div className="fontawesome-icons">
            <div className="like-font">
              <FontAwesomeIcon
                icon={faHeart}
                onClick={() => this.props.incrementLikesCount(post._id)}
              />
              <span>{this.props.likesCount}</span>
            </div>
            <div className="comment-font">
              <FontAwesomeIcon icon={faCommentAlt} />
            </div>
            <div className="share-font">
              <FontAwesomeIcon icon={faShareAlt} />
            </div>
          </div>
        </div>
      ));
  };

  render() {
    return (
      <div>
        <ul className="posts">{this.renderPosts()}</ul>
      </div>
    );
  }
}

const mapStateToProps = state => ({
  post: state.post.postDetail,
  likesCount: state.post.likesCount
});

export default connect(
  mapStateToProps,
  { fetchPosts, incrementLikesCount }
)(FeedPosts);

所以,基本上,我的问题是我如何才能仅针对特定帖子增加喜欢计数,因为我能够切换喜欢按钮,但它却增加了所有帖子的喜欢计数。

1 个答案:

答案 0 :(得分:1)

以下内容应该可以工作,但是将state.posts作为数组而不是每次都从数组转换为对象以及每次将对象转换为数组会更容易。

为确保其正常工作,您需要在设置state.posts的位置显示代码

case INCREMENT_LIKES_COUNT:
  return {
    ...state,
    likesCount:state.likesCount+1,
    //not sure why posts need to be an object instead of it being an array
    posts:Object.entries(state.posts).reduce(
      (result,[key,value])=>{

        if(value._id===action.payload){
          //you probably didn't set the initial likes but the reducer
          //  where you set state.posts isn't in your question
          result[key]= {...value,likes:value.likes+1};
        }else{
          result[key]=value;
        }
        return result;
      },
      {}
    )
  }

尽管再次看到这一点,但我意识到帖子是一个对象,其中id是键,因此您可以使其更简单:

case INCREMENT_LIKES_COUNT:
  return {
    ...state,
    likesCount:state.likesCount+1,
    //not sure why posts need to be an object instead of it being an array
    posts:{
      ...state.posts,
      [action.payload]:{
        ...state.posts[action.payload],
        likes:state.posts[action.payload].likes+1
      }
    }
  }