2015-04-02 47 views
1

tl; dr:GraphStore的UUID在每次向它添加新圖時發生變化。這導致我假設每個Graph都創建了自己獨特的GraphStore。我希望他們都分享一個商店。我有一個包含多個Graph組件的React Dashboard組件。迴流:有多個組件訪問相同的商店

我的Graph組件從儀表板傳遞了一個id道具。然後使用該ID,查找存儲在GraphStore中的圖形數組中的數據。但是,在我看來,每個Graph都創建了自己的GraphStore,而不是所有的共享相同的(所需的行爲)。我如何讓它們都使用相同的GraphStore?

我想過要從儀表板傳入正確的GraphStore,但是我不可能讓每個Graph都監聽GraphStore的更改。

我很高興不使用Reflux.connectFilter,但它似乎是完美的東西。

我的代碼(至少關鍵部位):

控制板

var React  = require('react'); 
var Graph  = require('./graph').Graph; 
var GraphActions = require('./graphActions').GraphActions; 
var UUID   = require('uuid'); 

var Dashboard = React.createClass({ 
    ... 
    render: function() { 
     var graphs = []; 
     for(var i = 0; i < 10; ++i) { 
      var id = UUID.v4(); 
      GraphActions.createGraph(id); 
      graphs.push(
       <Graph id={id} /> 
      ); 
     } 
    } 
}); 

module.exports = {Dashboard: Dashboard}; 

格拉夫

var React  = require('react'); 
var GraphStore = require('./graphStore').GraphStore; 

var Graph = React.createClass({ 
    mixins: [Reflux.connectFilter(GraphStore, "graph", function(){ 
     return graphs.filter(function(graph) { 
      return graph.id === this.props.id; 
     }.bind(this))[0]; 
    })], 
    propTypes: { 
     id: React.PropTypes.string 
    }, 
    render: function() { 
     // Needed because the AJAX call in GraphStore might not have completed yet 
     if(typeof this.state.graph == "undefined") { 
      return (<div>Graph loading...</div>); 
     } 

     return (<div>Data: {this.state.graph.data}</div>); 
    } 
}); 

module.exports = {Graph: Graph}; 

GraphStore

var Reflux  = require('reflux'); 
var jQuery  = require('jquery'); 
var GraphActions = require('./graphActions').GraphActions; 
var UUID   = require('uuid'); 

var GraphStore = Reflux.createStore({ 
    listenables: [GraphActions], 
    onCreateGraph: function(graphId) { 
     console.log("GraphStore " + this.id + " is adding new graph " + graphId); 

     jQuery.ajax({ 
       ... 
       success: this.addGraph 
     }); 
    }, 
    addGraph: function(data) { 
     this.graphs.push(
      { 
       id: graphId, 
       data: data 
      } 
     ); 

     this.trigger({graphs: this.graphs}); 
    }, 
    getInitialState: function() { 
     this.graphs = []; 

     // Here I give the store a UUID so I can identify it later 
     this.id = UUID.v4(); 

     return { 
      graphs: this.graphs 
     }; 
    } 
}); 

回答

5

getInitialState在Reflux Store每次訂購組件時都會觸發組件(這是組件的初始數據)。

如果你需要的東西是隻在店裏一次,使用init

var GraphStore = Reflux.createStore({ 
    listenables: [GraphActions], 
    init: function() { 
     this.graphs = []; 

     // Here I give the store a UUID so I can identify it later 
     this.id = UUID.v4(); 
    }, 
    getInitialState: function() { 
     return { 
      graphs: this.graphs 
     }; 
    } 
}); 
+0

這也解釋了這麼多,謝謝大家! – 2015-04-02 12:44:49

+0

很高興能幫到你:) – 2015-04-02 12:56:24