回流:有多个组件访问相同的商店

问题描述:

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

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