reducers
reducers同步方法的实现,app.model的原理
app.model({
namespace: 'counter',
state: { number: 0 },
// 同步的方法
reducers: {
// state是之前的状态,return返回值是新状态 state
add(state, action) {
window.console.log('action', action);
return { number: state.number + (action.payload || 10) };
},
minus(state) {
return { number: state.number - 2 };
},
},
});
app._models
[
{
namespace: 'counter',
state: { number: 0 },
// 同步的方法
reducers: {
// state是之前的状态,return返回值是新状态 state
add(state, action) {
window.console.log('action', action)
return { number: state.number + (action.payload || 10) }
},
minus(state) {
return { number: state.number - 2 }
},
},
},
{
namespace: 'list',
state: { number: 0 },
reducers: {
// state是之前的状态,return返回值是新状态 state
add(state, action) {
window.console.log('action', action)
return { number: state.number + (action.payload || 10) }
},
minus(state) {
return { number: state.number - 2 }
},
},
}
]
app.model的实现
import { combineReducers, createStore } from 'redux';
function createReducers(app) {
const rootReducers = {}
for(const model of app._models) {
const {namespace, reducers } = model;
// state要有一个初始化的值
// action = dispatch({ type: 'counter/add' })
rootReducers[namespace] = (state = model.state, action) => {
// action.type: 'counter/add'
const [namespace: name, type] = action.type.split('/');
// 判断命名空间
if(namespace === name) {
// 当前命名空间下,是否有这个属性,有这个函数就调用
const reducer = reducers[type];
if(reducer) return reducer(state, action);
}
return state;
}
}
return combineReducers(rootReducers);
}
app.start
createStore
const rootReducers = createReducers(app);
createStore(rootReducers);