jeudi 4 avril 2019

React ComponentDidUpdate runs every second and condition not working

I have a React component with componentWillUpdate in this lifecycle method I call an action, the action has a console.log in it.

I have Two questions:

  1. why is the componentWillUpdate runs every second?

  2. why the if in the componentWillUpdate is not working? shouldn't it run only when the props are not the same?

this is the component code:

** updated **

     import React, { Component } from "react";
import { connect } from "react-redux";
import { fetchCourses } from "../../actions";

class Courses extends Component {
  componentDidMount() {
    this.props.fetchCourses();
  }

  componentWillUpdate(prevProps) {

    if (this.props.courses !== prevProps.courses) {
      console.log('prevProps.courses ', prevProps.courses);
      console.log('this.props.courses ', this.props.courses);
      this.props.fetchCourses();
    }
  }

  render() {
    console.log('this.props.payload.courses ', this.props.courses);
    const courses = this.props.courses.map(course => {
      return (
        <tr>
          <td>{course.coursename}</td>

          <td>{course.coursetype ? "yes" : "no"}</td>

          <td>{course.courseweeklyhours}</td>

          <td>
            <button>הסר</button>
          </td>
        </tr>
      );
    });

    return (
      <div>
        Courses
        {courses}
      </div>
    );
  }
}

const mapStateToProps = state => {
  // console.log('state ', state);

  return {
    courses: state.courses
  };
};

export default connect(
  mapStateToProps,
  { fetchCourses }
)(Courses);

Courses returns an array

enter image description here

Aucun commentaire:

Enregistrer un commentaire