Не получает обновленное состояние - PullRequest
0 голосов
/ 04 августа 2020

Я использую стек MERN и Redux. Когда я вызываю функции fetchSubject () и fetchComments, глобальное состояние обновляется. Я вижу это в Redux devTools, что он сделал как надо. Моя проблема в том, что когда я пытаюсь получить доступ к глобальному состоянию, оно возвращает исходное состояние, а не обновленное. Есть идеи, как это решить?

import React, { Component } from "react";
import PropTypes from "prop-types";
import GoogleSearch from "./GoogleSearch";
import { connect } from "react-redux";
import { fetchSubjects } from "../../actions/subject";
import { fetchComments } from "../../actions/comment";
import store from "../../store";

class Subject extends Component {
  // on loading the subjects will be fetched
  componentDidMount() {
    this.props.fetchSubjects();
    this.props.fetchComments();
    console.log(store.getState().comments);
  }

  constructor(props) {
    super(props);
    this.state = {
      // set inital state to not show
      viewDescription: -1,
      viewSummary: -1,
    };
  }

  // add new subject and comments are added to the top of comments
  componentWillReceiveProps(nextProps) {
    if (nextProps.newPost) {
      this.props.subjects.unshift(nextProps.newPost);
    }
    if (nextProps.newPost) {
      this.props.comments.unshift(nextProps.newPost);
    }
  }

  // only apply to the id that has been clicked
  // if false set to -1 if true set to id
  clickHandler = (id) => {
    const { viewDescription } = this.state;
    this.setState({ viewDescription: viewDescription === id ? -1 : id });
    // this gets the comments for only the subject id that has been clicked

    console.log(id);
    localStorage.setItem("passedSubject", id);
  };

  hoverHandler = (id) => {
    this.setState({ viewSummary: id });
    // console.log("Hovered");
  };

  hoverOffHandler = () => {
    this.setState({ viewSummary: -1 });
    // console.log("Hovered off");
  };

  render() {
    const subjectItems = this.props.subjects.map((subject) => {
      // if the state equals the id set to visible if not set to invisible
      var view = this.state.viewDescription === subject._id ? "" : "none";
      var hover = this.state.viewSummary === subject._id ? "" : "none";
      return (
        <div key={subject._id}>
          <div
            className="subjectTitle"
            onClick={() => this.clickHandler(subject._id)}
            onMouseEnter={() => this.hoverHandler(subject._id)}
            onMouseLeave={() => this.hoverOffHandler()}
          >
            <p className="title">{subject.title}</p>
            <p className="rating">Rating: {subject.rating}</p>
            <p className="summary" style={{ display: hover }}>
              {subject.summary}
            </p>
          </div>

          <div className="subjectBody " style={{ display: view }}>
            <div className="subjectAuthor">
              <p className="author">
                Subject created by: {subject.author} on {subject.date}
              </p>
              <a href="">
                <div className="buttonRateSubject">RATE SUBJECT</div>
              </a>
            </div>

            <div className="subjectDescription">
              <p className="description">{subject.description}</p>
            </div>

            <div className="subjectLinks">Links:</div>

            <div className="subjectComments">
              <p>Comments:</p>
              <p>{subject.comments}</p>
              <a href="/addcomment">
                <div className="buttonAddComment">ADD COMMENT</div>
              </a>
            </div>
          </div>
        </div>
      );
    });

    return (
      <div id="Subject">
        <GoogleSearch />
        {subjectItems}
      </div>
    );
  }
}

Subject.propTypes = {
  fetchSubjects: PropTypes.func.isRequired,
  fetchComments: PropTypes.func.isRequired,
  subjects: PropTypes.array.isRequired,
  comments: PropTypes.array.isRequired,
  newPost: PropTypes.object,
};

const mapStateToProps = (state) => ({
  subjects: state.subjects.items,
  newSubject: state.subjects.item,
  comments: state.comments.items,
  newComment: state.comments.item,
});

// export default Subject;
export default connect(mapStateToProps, { fetchSubjects, fetchComments })(
  Subject,
  Comment
);
...