簡體   English   中英

React - componentWillReceiveProps 條件不呈現組件中的數據

[英]React - componentWillReceiveProps condition doesn't render the data in the component

我有一個帶有componentWillReceiveProps實時循環方法的componentWillReceiveProps 在組件內部,我可以成為一個動作創建者。

據我了解componentWillReceiveProps呈現組件的每一秒。 出於這個原因,我添加了一個條件,僅當this.props不等於prevProps時才激活組件渲染。

出於某種原因,每次道具更新時this.props.fetchCourses(); componentWillReceiveProps內部不呈現。 以及我沒有看到 console.log 結果。什么點表明塊不是 p

我正在使用fast-deep-equal庫來比較對象,但我願意接受建議。

我的問題是為什么更新 props 時組件不呈現。

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);

我的建議是你真的不希望 componentWillReciveProps() 觸發 fetch 課程......每當你在課程中執行(創建,更新,刪除等)等操作時,在每個功能之后觸發 fetch course 動作......它會自動更新 redux-store 和組件(課程)將自動更新。

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();  

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM