Question: How can I change the reflux listenTo mixin based on a prop in a react.js component

Question

How can I change the reflux listenTo mixin based on a prop in a react.js component

Answers 2
Added at 2016-04-08 13:04
Tags
Question

Can anyone help with this...

I have this list component and I want to be able to switch different data stores (defined in props)

mixins:[Reflux.listenTo(RecentPupilsStore, 'onChange')],

But I want to do this -

mixins:[Reflux.listenTo(this.props.store, 'onChange')],

But props don't appear to be available in the mixin. I also tried to transfer it to a function:

mixins:[Reflux.listenTo(this.setStore(this.props.store), 'onChange')],
setStore: function(store){
    if(store == 'RecentPupilsStore') { return RecentPupilsStore; }
},

Any help appreciated. pretty new ot react but trying to make it as reusable as possible!

EG: I want to include the component like this:

<FilterList data="pupils" />
<FilterList data="groups" />

etc - and these would look at these stores.

Answers to

How can I change the reflux listenTo mixin based on a prop in a react.js component

nr: #1 dodano: 2016-04-08 16:04

I would pass on using the mixin and just listen to both stores and map your data accordingly.

  componentDidMount = () => {
    // console.log('AppCtrl componentDidMount');
    this.unsubscribeApp = AppStore.listen(this.appStoreDidChange);
    this.unsubscribeGS = GenusSpeciesStore.listen(this.gsStoreDidChange);
  };
  componentWillUnmount = () => { this.unsubscribeApp(); this.unsubscribeGS(); };
  appStoreDidChange = () => { this.setState(getAppState()); };
  gsStoreDidChange = () => { this.setState(getGsState()); };

nr: #2 dodano: 2016-04-12 15:04

I won't say that this is the best solution, but it gives an answer to your question on how to use props to define the name of the store to listen to.

You don't need to define the store and method where you apply the Mixin. You can make use of the more general 'Reflux.ListenerMixin' and combine that with the registration of the listener in 'ComponentDidMount'.

var MyComponent = React.createClass({
    mixins: [Reflux.ListenerMixin],
    // Lifecycle events
    componentDidMount: function() {
        var theStore = defineTheStore(this.props.data);
        this.listenTo(theStore, this.onChange);
    },
    render: function() {
        return(
            <div >
                ....
            </div>
        );
    },
    onChange: function() {

    }
});
Source Show
◀ Wstecz