Chen Jian's Java Blog 

Redux weird thing 3 - Action Creator

by Chen Jian


Posted on 2018-06-20 12:27 in Frontend


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



No one has commented yet.
该日志评论功能被禁用了。