redux学习笔记
- 每一个reducer函数都由两个参数state, action构成.其中state表示一个状态,即数据的状态.state!=undefined,表示要对state进行修改,并返回一个新的state. action表示一个操作,通常用type来进行区分,其它属性用于新state的属性分配.如以下代码:
const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
name: action.name,
completed: false
};
case 'TOGGLE_TODO':
return state.id === action.id ?
Object.assign({}, state, {
completed: !state.completed
}) :
state;
default:
return state;
}
};
const todo = (state, action) => {
switch (action.type) {
case 'ADD_TODO':
return {
id: action.id,
name: action.name,
completed: false
};
case 'TOGGLE_TODO':
return state.id === action.id ?
Object.assign({}, state, {
completed: !state.completed
}) :
state;
default:
return state;
}
};
const todos = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
todo(state, action)
];
case 'TOGGLE_TODO':
return state.map(t => {
return todo(t, action);
});
default:
return state;
}
};
//合并reducer的手写实现 redux.combineReducers
const combineReducers = (reducers) => {
return (state = {}, action) => {
//Array.prototype.reduce(callback, initialValue);
//callback四个参数, prev,cur,index,arr
//initialValue表示设置的初始值
return Object.keys(reducers).reduce((nextState, key) => {
// console.log(nextState);
nextState[key] = reducers[key](state[key], action);
// console.log(nextState);
return nextState;
}, {});
};
};
const todosApp = combineReducers({
todos,
visibilityFilter
});