Redux weird thing 3 – Action Creator

You can dispatch an action inside your component, for example, when a button is clicked, like

 
    render(){
        return (

            <div>
               ...
                <div>
                    <button onClick={ e =>  this.context.store.dispatch({type: 'counterChange', amount:  1}) }> + </button>
                    <button onClick={ e =>  this.context.store.dispatch({type: 'counterChange', amount: -1}) }> - </button>
                </div>
            </div>
        );
    }

 

But a more preferred way is to extract the action creation logic as another function.

function counterChangeAction(amount){
    return {
        type: 'counterChange',
        amount: amount
    }
}


class CounterComponent extends Component {
    constructor(props){
        super(props);
    }

    render(){
        return (

            <div>
                <h2>Counter</h2>
                <h3>{this.context.store.getState().counter.value}</h3>
                <div>
                    <button onClick={ e =>  this.context.store.dispatch(counterChangeAction(1)) }> + </button>
                    <button onClick={ e =>  this.context.store.dispatch(counterChangeAction(-1)) }> - </button>
                </div>
            </div>
        );
    }

}

You will get documenting benefits if you put all the actions together, just like you get the benefits when you put all the sql together in IBatis

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.