簡體   English   中英

我應該在React中遵循什么樣的設計模式?

[英]What design pattern should I follow in React?

我創造了超過一千個svg元素。 在刪除,更新或選擇單個元素時,它在時間上非常昂貴。 因為當我刪除或更新特定的svg元素時,它會re-renders整個父節點,其中包含所有數十億個子節點。 這是添加元素和渲染的代碼。

var App = React.createClass({
  getInitialState: function() {
    return {
      propsList: []
      };
   },
  addProps: function(props) {
    var propsList = this.state.propsList.concat([props]);
      this.setState({ propsList: propsList });
        },
  render: function() {
    var components = this.state.propsList.map(function(props) {
      return React.createElement('g', props);
        });
    return React.createElement('div', null, components);
      }
  });
  ReactDOM.render(
      React.createElement(App, null),
      document.getElementById('svg')
    );

請建議一個可以解決我的問題的design pattern 因此,當我添加或刪除元素時,父節點不必re-render因為它包含數千個子節點。

您可以嘗試緩存元素的渲染,如果它們的渲染確實是減慢應用程序速度的部分:

var App = React.createClass({

  getInitialState: function() {
    return {
      cachedElements: [],
      propsList: []
    };
  },

  addProps: function(props) {
    var propsList = this.state.propsList.concat([props]);
    var cachedElements = this.state.cachedElements.concat([
      React.createElement('g', props)
    ])
    this.setState({ 
      cachedElements: cachedElements,
      propsList: propsList 
    });
  },

  render: function() {
    return React.createElement('div', null, this.state.cachedElements);
  }
});

我沒有從狀態中刪除propsList,如果它沒有用於渲染組件,你應該這樣做。 您可以使用模塊變量或組件屬性,或者只是在不需要同時訪問所有項目時將其完全刪除 - 但我想如果您想要完整的CRUD操作,則需要訪問它們。

暫無
暫無

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

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