redux入门指南(二)
作者:Jogis 第一篇介绍的是redux作为状态容器的核心思想,由 storeredux里面,store实例拥有四个方法: 精简后的store创建代码非常简单: function createStore(reducer,initialState){ let currentState = initialState; return { getState: () => currentState,dispatch: action => { currentState = reducer(currentState,action) } } } reducer
比如一个动物园有猫和狗,现在需要添加一些猫猫狗狗: function cat(state = [],action){ if(action.type === constant.ADD_CAT){ state.push(action.cat); return state; }else { return state; } } function dog(state = [],action){ if(action.type === constant.ADD_DOG){ state.push(action.dog); return state; }else { return state; } } //添加Tom猫 dispatch({ type: constant.ADD_CAT,cat: { name: 'Tom' } }); //添加Jerry狗 dispatch({ type: constant.ADD_DOG,dog: { name: 'Jerry' } }); 之前提及到的是单一数据源原则,一个应用应该只有一个数据源(state),但是一个reducer会产生一个 比如: //homeAnimals就成为一个reducers const homeAnimals = combineReducers({cat,dog}); // nextState: // { // cat: [{...}],// dog: [{...}] // } const nextState = homeAnimals(state,action); 更高层级的状态树: cons zoo = combineReducers(homeAnimals,otherAnimals); // nextState: // { // homeAnimals: {...},// otherAnimals: {...} // } const nextState = zoo(state,action); 合成的reducer 未完待续... (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |