就是将上篇文章中的/src/store.js文件放到一个目录下进行多个拆分
这里dispatch处写错了 应该是dispatch派发内容的封装
原store.js
import { createStore, combineReducers } from "redux";
function counter(state = { count: 1 }, action) {
console.group("counter reducer");
console.log(state);
console.log(action);
console.groupEnd();
/* action.type的值必须是唯一的,不可以重复 */
switch (action.type) {
case "ADD":
return { ...state, count: state.count + action.payload.step };
default:
return state;
}
}
function product(state = { list: [], page: 1 }, action) {
console.group("product reducer");
console.log(state);
console.log(action);
console.groupEnd();
switch (action.type) {
/* case value:
break; */
default:
return state;
}
}
const lastReducer = combineReducers({
/* 属性名:属性值,其中属性名可以改变 */
counter: counter,
product: product,
});
const store = createStore(
lastReducer,
// 截图有步骤
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
); // 创建一个store
// 初始化加载
console.log(store.getState());
store.dispatch({
type: "ADD",
payload: {
step: 3,
},
});
console.log(store.getState());
export default store;
拆分后的
/src/store/actions/counter.js 派发的dispatch内容封装成了一个函数
export function addAction(step) {
return {
type: "ADD",
payload: {
step,
},
};
}
// 上下两种写法一致
export const reduceAction = (step) => ({
type: "REDUCE",
payload: {
step,
},
});
/src/store/reducers/counter.js 定义function也就是reducer
// 定义reducer的时候它是一个function 接收两个参数
// 参数一 初始状态
// 参数二 action 表示以什么方式改变数据
export default function counter(state = { count: 1 }, action) {
console.group("counter reducer");
console.log(state);
console.log(action);
console.groupEnd();
/* action.type的值必须是唯一的,不可以重复 */
switch (action.type) {
case "ADD":
return { ...state, count: state.count + action.payload.step };
case "REDUCE":
return { ...state, count: state.count - action.payload.step };
default:
return state;
}
}
/src/store/reducers/product.js 定义function也就是reducer
export default function product(state = { list: [], page: 1 }, action) {
console.group("product reducer");
console.log(state);
console.log(action);
console.groupEnd();
switch (action.type) {
/* case value:
break; */
default:
return state;
}
}
/src/store/reducers/index.js 合并reducer
import { combineReducers } from "redux";
import counter from "./counter";
import product from "./product";
export default combineReducers({
counter,
product,
});
/src/store/index.js 创建store
import { createStore } from "redux";
import lastReducer from "./reducers/index";
const store = createStore(
lastReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
export default store;
简洁举例