I have a component with componentWillReceiveProps
live cycle method. inside the component, I can an action creator.
As far as I understand the componentWillReceiveProps
renders the component every second. for that reason I added a condition to activate the component render only when this.props
does not equal prevProps
.
for some reason every time the props are updated the this.props.fetchCourses();
inside the componentWillReceiveProps
is not rendered. as well I don't see the console.log result.What points that the block is not p
I am using fast-deep-equal
library to compare the objects but I am open to suggestions.
my question is why the component does not render when props are updated.
import React, { Component } from "react";
import { connect } from "react-redux";
import equal from "fast-deep-equal";
import { fetchCourses, deleteCourse } from "../../actions";
class Courses extends Component {
componentDidMount() {
this.props.fetchCourses();
}
componentWillReceiveProps(prevProps) {
console.log(this.props.courses);
console.log(prevProps.courses);
if (!equal(this.props.courses, prevProps.courses)) {
this.props.fetchCourses();
}
}
render() {
const prevProps = prevProps => {
console.log("this.props", this.props.courses.length);
console.log("prevProps ", prevProps.courses.length);
};
const courses = this.props.courses.map(course => {
return (
<tr key={course && course.id}>
<td>
{course.coursename}- {course && course.id}
</td>
<td>{course.coursetype ? "yes" : "no"}</td>
<td>{course.courseweeklyhours}</td>
<td>
<button
onClick={() => this.props.deleteCourse(course && course.id)}
>
הסר
</button>
</td>
</tr>
);
});
return <tbody>{courses}</tbody>;
}
}
const mapStateToProps = state => {
console.log("state ", state);
return {
courses: state.courses
};
};
export default connect(
mapStateToProps,
{ fetchCourses, deleteCourse }
)(Courses);
my suggestion is you really do not want componentWillReciveProps() to trigger the fetch course... whenever you do operation like (create, update, delete , etc..) in courses, trigger the fetch course action after each functionality.. it will automatically update the redux-store and component(Courses) will update automatically.
handleCreateCourse = async (values)=>{
//logics for create courses and api call
await createCourse(values);
//trigger your fetchCourses action here
//it will update your other components where you listened courses from redux.
this.props.fetchCourses();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.