我正在使用Reflux.connectFilter mixin使一堆Graph组件监听我的GraphStore中的更改。使用过滤器,仅当GraphStore的graphs数组中匹配其ID的元素发生更改(或添加/删除)时,它们才应重新呈现。但是,当我更新数组的单个元素时,比如说通过设置名称变量,我仍然看到所有监听图都重新呈现。难道我做错了什么?
GraphStore
var Reflux = require('reflux');
var GraphActions = require('./graphActions').GraphActions;
var GraphStore = Reflux.createStore({
listenables: [GraphActions],
init: function() {
this.graphs = [];
this.metricMetaData = {};
},
onAddGraph: function(graphId, name) { // Called only by the Dashboard component that is a parent to all Graphs
this.graphs.push(
{
id: graphId,
name: ""
}
);
this.updateGraphs();
},
onSetName: function(graphId, name) { // Called only by the Dashboard component that is a parent to all Graphs
for(var i = 0, gl = this.graphs.length; i < gl; ++i) {
if(this.graphs[i].id === graphId) {
this.graphs[i].name = name;
this.updateGraphs();
return;
}
}
},
...
updateGraphs: function() {
this.trigger(this.graphs); // This is the only place in the store where trigger is called
},
getInitialState: function() {
return this.graphs;
}
});
module.exports = {GraphStore: GraphStore};
图形
/** @jsx React.DOM */
var React = require('react');
var Reflux = require('reflux');
var GraphActions = require('./graphActions').GraphActions;
var GraphStore = require('./graphStore').GraphStore;
var Graph = React.createClass({
mixins: [Reflux.connectFilter(GraphStore, "graph", function(graphs) {
return graphs.filter(function(graph) {
return graph.id === this.props.id;
}.bind(this))[0];
})],
propTypes: {
id: React.PropTypes.string.isRequired
},
...
render: function() {
if(typeof this.state.graph === "undefined") {
return (<div>The graph has not been created in the store yet</div>);
} else {
return (<div>Graph name: {this.state.graph.name}</div>);
}
}
};
module.exports = {Graph: Graph};
仪表板
/** @jsx React.DOM */
var React = require('react');
var Graph = require('./graph').graph;
var GraphActions = require('./graphActions').GraphActions;
var UUID = require('uuid');
var Dashboard = React.createClass({
propTypes: {
numGraphs: React.PropTypes.int.isRequired
},
...
render: function() {
var graphs = [];
for(var i = 0; i < this.props.numGraphs; ++i) {
var currId = UUID.v4();
GraphActions.addGraph(currId, "");
graphs.push(<Graph id={currId} />);
}
return (<div>{graphs}</div>);
}
};
module.exports = {Dashboard: Dashboard};
最佳答案
我没有使用Reflux,但是我认为这里的问题是您所有的Graph
实例都在监听GraphStore
,并且一旦该存储发送事件,所有组件实例都将接收该事件。他们将过滤掉不感兴趣的数据,但是Reflux仍将在所有实例上调用setState
,触发它们重新渲染。如果过滤器功能的结果与以前相同,则Reflux不会(据我所知)重新短路短路。
为了使它短路并避免在返回相同数据时重新呈现,需要在组件上实现shouldComponentUpdate
方法,并将新状态与旧状态进行比较,如果相同则返回false。
一种流行的方法是将[1] Immutable.js与[2] PureRenderMixin一起使用,它会为您实现短路。
[1] https://github.com/facebook/immutable-js
[2] https://facebook.github.io/react/docs/pure-render-mixin.html
关于javascript - reflux connectFilter仍向所有监听组件发送更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29709388/