12/08/2018, 15:25

[React] Cách gọi và làm việc trực tiếp với 1 component cụ thể (render).

Trong bài toán với mô hình như sau: Bình thường khi addition_category có sự thay muốn render lại categories_object thì sẽ phải render lại condition_form => không tốt, Phương pháp: component cha sẽ chứa tất cả các con trỏ của các object con. Khi muốn render lại chỉ cần tìm lần lượt theo các ...

Trong bài toán với mô hình như sau: Bình thường khi addition_category có sự thay muốn render lại categories_object thì sẽ phải render lại condition_form => không tốt,

Phương pháp: component cha sẽ chứa tất cả các con trỏ của các object con. Khi muốn render lại chỉ cần tìm lần lượt theo các key.

1)Mỗi 1 object sẽ khai báo 2 function:

handleRefresh(keys, data = {}){
    var object = null;
    if(!Array.isArray(keys)){
      this.objectRefresh[keys].refreshObject(data);
      return;
    }
    for(var key of keys){
      object = object ? object.objectRefresh[key] : this.objectRefresh[key];
    }
    object ? object.refreshObject(data) : {};
  }

  handleRegisterRefresh(key, object){
    this.objectRefresh[key] = object
  }
  • handleRegisterRefresh(key, object): Đăng kí key với component cha

  • handleRefresh(keys, data = {}): Yêu cầu render lại component có thứ tự là keys keys: là string => component tại key=keys của this.objectRefresh keys là array => tìm lần lượt theo thứ tự trong mảng, mò dần xuống để tìm object.

  • data là dữ liệu cần reset.

    vd: keys=['condition_form', 'categories_object'] => component có key là 'categories_object' của component có key là 'condition_form' của this.objectRefresh

truyền 2 hàm này làm props cho các component con. => 2 hàm này có thể chuyển thành class functions để ko phải khai báo nhiều.

2)function refreshObject. vd:

refreshObject(data){
    this.setState({
      current_categories: data.current_categories,
      temp_categories:
        this.removeAlreadySelected(this.props.categories, data.current_categories)
    });
  }

=> Set lại dữ liệu cho object, data được truyền từ handleRefresh vào.

  1. Thực tế. -modal_testrule:
 export default class Modal extends React.Component {
  constructor(props) {
    super(props);
    this.objectRefresh = {};
  }
  • this.objectRefresh chứa các component con của Modal. Ở đây là: -condition_form:
export default class ConditionForm extends React.Component {
 constructor(props) {
   super(props);
   this.objectRefresh = {};

   this.props.handleRegisterRefresh('condition_form', this);
 }}

-addition_category:

export default class AdditionFormCategory extends React.Component {
  constructor(props) {
    super(props);
    this.props.handleRegisterRefresh('addition_category', this);
  }}

Tương tự condition_form chứa 4 component con: categories_object, questions_object , categoty_preivew, question_preview

Khi ở addition_category muốn render lại categories_object => this.props.handleRefresh(['condition_form', 'categories_objects'], {refresh: true})

0