对redux的理解

redux文件中:

redux文件中,需要作两件事:
1、由dispatch来的事件找到对应的action。
2、如何将事件中的参数映射到redux的store的state中去。

redux的store有state和actions。


定义actions:
下面将 hideDialog的dispatch 和type为HIDE_DIALOG的Action关联起来。
也就是如果向store dispatch一个hideDialog的消息,
则由store中的HIDE_DIALOG Action 来处理。
则store中type为HIDE_DIALOG
export const actions = {
    hideDialog: dispatch => {
        dispatch({
            type: HIDE_DIALOG,
        });
    }
};

初始化redux的store中的state:
下面的dialog是state中的一项。
const INITIAL = {
    dialog: {
        title: '',
        message: '',
        button: [],
        show: false
    }
};


//收到action后,如何用action参数中的值去改变redux的state的值.
也就是如何将随action而来的值映射到store的state中。
export default (state = INITIAL, action) => {
    switch (action.type) {
    case SHOW_DIALOG:
            return Object.assign({}, state, {
                dialog: {
                    title: action.title,
                    message: action.message,
                    button: action.button || [],
                    show: true
                }
            });
        case HIDE_DIALOG:
            return Object.assign({}, state, {
                dialog: {
                    title: '',
                    message: '',
                    button: [],
                    show: false
                }
            });


        default:
            return state;
    }
};



在component中:

/*
component通过下面的方法接收消息。
component收到消息后,component中的componetProperty属性将被
消息改变。

下面的方法将component的componetProperty属性映射到redux的state.app.dialog。
下面方法的主语是redux。
map redux 的 state to component 的 props

通过将redux的state映射到component的属性,
改变redux的state,就相当于component收到了消息。
redux通过改变自己的state向componet发送消息。
redux的state的改变就相当于改变了component的props。
component 通过 自己的props被改过,接收到消息。

*/
const mapStateToProps = (state) => ({
    componetProperty: state.app.dialog
});

/*
component通过下面的方法向外发布消息。
也就是component通过redux向外发布消息。
所发布消息的type是:Category.actions.addCategory
component通过调用自己 componentProperty(name) 方法,
就发布了此消息。

下面方法的主语是redux。
map redux 的 dispatch to 当前componet 的Props。

=>的左侧:
componentProperty: (name) 
是 component的Props

=>的右侧:
Category.actions.addCategory(dispatch)({ name })
是Redux中定义的action。


*/
const mapDispatchToProps = (dispatch, ownProps) => ({
    componentProperty: (name) => Category.actions.addCategory(dispatch)({ name })


redux由 state 和 action组成。 
Action 是一个对象。其中的type属性是必须的,表示 Action 的名称。其他属性可以自由设置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值