The idea with flux is that you set your React component's internal state (or part of it) to an object or value from a store every time that store changes.
So for example something like this (not real code, but to give you an idea):
var Component = react.createClass({
getInitialState: function() {
return {
items: Flux.getStore("ItemStore").getItems()
}
},
componentDidMount: function() {
this.store = Flux.getStore("ItemStore");
this.store.addChangeListener(this.onStoreChange)
},
componentWillUnmount: function() {
this.store.removeChangeListener(this.onStoreChange);
},
onStoreChange: function() {
this.setState({
items: this.store.getItems()
});
},
render: function() {
var items = [];
for (var i = 0; i < this.state.items; i++) {
items.push(
<li key={i}>{this.state.items[i]}</li>
);
}
return (
<ul>{items}</ul>
);
}
});
What this example component does is render a list of this.state.items
that reside in a store called ItemStore
and are accessed by ItemStore.getItems()
. So take a look at the componentDidMount
which gets the store, binds a callback to whenever the store is changed onStoreChange
and then sets the current component state of items
to the items array provided by store.getItems()
.
As a result when the component is first mounted it gets the current items from the store and displays them, whenever the store changes it will execute onStoreChange
which gets the items again from the store and sets them again via this.setState()
.
Naturally we want to be clean so this component also removes the onStoreChange
binding when the component is being unmounted.
Note: Remember that calling this.setState()
inside componentDidMount
does not cause a component re-render :)
More on this in the facebook-flux documentation here: http://facebook.github.io/flux/docs/todo-list.html#listening-to-changes-with-a-controller-view