2016-10-03 4 views
0

新しいインスタンスを作成する代わりにストアドバージョンを使用できるように、各インスタンスのインスタンスをチェックしてチェックしたいのですが、どのようにリストをチェックするためにリストを保持することができますか?React状態を使用して、すでにインスタンス化されたオブジェクトのリストを管理しますか?

サンプルコード:

export default React.createBackboneClass({ 

    getInitialState() { 
     return { 
      data: [], 
      groups: {} 
     } 
    }, 

    componentWillMount() { 
     this.setState({ 
      data: this.props.collection 
     }); 
    }, 

    render() { 
     const gridGroups = this.state.data.map((model) => { 

      let gridGroupsCollection = null; 

      if(this.state.groups[model.get('id')]) { 
       gridGroupsCollection = this.state.groups[model.get('id')]; 
      } else { 
       gridGroupsCollection = this.state.groups[model.get('id')] = new GridGroupCollection([], { 
        groupId: model.get('id') 
       }); 

       this.setState((previous) => { 
        groups: _.extend({}, previous, gridGroupsCollection) 
       }); 
      } 

      return <GridGroupComponent 
       key={model.get('id')} 
       name={model.get('n')} 
       collection={gridGroupsCollection} /> 
     }); 

     return (
      <div> 
       {gridGroups} 
      </div> 
     ); 
    } 
}); 

答えて

0

いくつかのポイント。まず第一に、コンポーネントWillReviewPropsを使用して重い作業を行います。 レンダリングメソッドでこれを行う方がコストがかかる可能性があります。私はまだ状態オブジェクトにインスタンスを保存する必要があります。パフォーマンス上のキャッシュやソートの問題の解決に必要ですか?

さらに、既に述べたように、renderメソッドからsetStateを呼び出すと、無限ループが生成されます。状態が変化したときにrenderが呼び出されるためです。

これは、データ操作からコンポーネントを分離するためのいくつかの包括的な方法を提供する、私はReduxと考えています。 、ちょっと

componentDidMount: function() { 
     // Whenever there may be a change in the Backbone data, trigger a 
     // reconcile. 
     this.getBackboneCollections().forEach(function (collection) { 
      // explicitly bind `null` to `forceUpdate`, as it demands a callback and 
      // React validates that it's a function. `collection` events passes 
      // additional arguments that are not functions 
      collection.on('add remove change', this.forceUpdate.bind(this, null)); 
     }, this); 
    }, 

    componentWillUnmount: function() { 
     // Ensure that we clean up any dangling references when the component is 
     // destroyed. 
     this.getBackboneCollections().forEach(function (collection) { 
      collection.off(null, null, this); 
     }, this); 
    } 
+0

返事に感謝が、私は原因レンダリングの状態を設定するには、エラーを取得する - 警告:

更新

This TodoMVC exampleは反応し結合し、バックボーンする方法の方向にあなたを指している可能性があります.js:36警告:setState(...):既存の状態遷移( 'render'や他のコンポーネントのコンストラクタ内など)中には更新できません。レンダリング方法は、小道具と州の純粋な機能でなければなりません。コンストラクタの副作用はアンチパターンですが、 'componentWillMount'に移動することができます。 – styler

+0

これは、renderメソッドのsetStateの呼び出しが無限ループを開始するために必要です。レンダリングメソッドの状態を変更して無限ループを開始すると、状態が変更されるとレンダリングが自動的に呼び出されます。 – Guy

+0

ねえ、これを修正するにはどうすればthis.getCachedGridGroupCollectionは基本的にやっているのですか? – styler

関連する問題