[js] redux foundation
// actions.js
export default function todos(type, a, b) {
return {
type,
a,
b
}
}
// reducers.js
export default function todoApp(state, action) {
switch (action.type) {
case 'add':
return Object.assign({}, state, {
result : action.a + action.b
})
case 'sub':
return Object.assign({}, state, {
result : action.a - action.b
})
default:
return state
}
}
Store管理state的变化
维持应用的 state;
提供 getState() 方法获取 state;
提供 dispatch(action) 方法更新 state;
通过 subscribe(listener) 注册监听器;
通过 subscribe(listener) 返回的函数注销监听器。
可以说store是真正的state管理者,其他的,如action是命令,reducer是执行命令的士兵。
// store.js
import { createStore } from 'redux';
import { todos } from './actions';
import { todoApp } from './reducers.js';
let store = createStore(todoApp);
// 打印初始状态
console.log(store.getState())
// 每次 state 更新时,打印日志
// 注意 subscribe() 返回一个函数用来注销监听器
let unsubscribe = store.subscribe(() =
console.log(store.getState())
)
// 发起一系列 action
store.dispatch(todos('add', 100, 99));
store.dispatch(todos('sub' ,100, 99));
// 停止监听 state 更新
unsubscribe();
combineReducers,合并多个reducer
如有下面两个reducer,todoApp,textApp
// reducers/todoApp.js
export default function todoApp(state, action) {
switch (action.type) {
case 'add':
return Object.assign({}, state, {
result : action.a + action.b
})
case 'sub':
return Object.assign({}, state, {
result : action.a - action.b
})
default:
return state
}
}
// reducers/textApp.js
export default function todoApp(state, action) {
switch (action.type) {
case 'normal':
return Object.assign({}, state, {
result : action.text
})
case 'camel':
return Object.assign({}, state, {
result : action.text.replace(/-[^-]{1}/g, (m) => m[1].toUpperCase())
})
default:
return state
}
}
换成combineReducers,则为
// reducers/index.js
import { combineReducers } from 'redux';
import textApp from './textApp';
import todoApp from './todoApp';
export default combineReducers({
textApp,
todoApp
});
则调用时可以写成这样
import reducer from './reducers'
let store = createStore(reducer);