一、创建目录
二、拆分 reducer
1)创建 reducer
// state 的初始值
const initState = 0;
const countReducer = (state = initState, { type, payload }) => {
switch (type) {
default: return state;
}
}
export default countReducer;
2)合并 reducer
每一个应用中,数据都不止一条,因此 reducer 也不止一个。因此,在将 reducer 传递给 store 之前,需要对所有的reducer 做一个合并处理。
在 redux 目录中创建一个 combineReducers.js 文件,用来处理 reducer 的合并。
import { combineReducers } from 'redux';
import countReducer from './counter/reducers.js'
export default combineReducers({
// 该对象的键名会作为 reducer 中数据在仓库中的名字
count: countReducer
});
3)仓库引入 reducer
import { createStore } from "redux";
import combineReducers from './combineReducers.js'
const store = createStore(combineReducers);
三、拆分 action
1)创建 action 对象
export const incrementAction = () => {
return {
type: 'increment'
}
}
export const decrementAction = () => {
return {
type: 'decrement'
}
}
export const inputCountAction = payload => {
return {
type: 'inputCount',
payload
}
}
2)提取 type 值
在对应的模块中创建 actionTypes.js 文件,用来保存当前模块中所有 action 的 type 值
const INCREMENT = 'increment';
const DECREMENT = 'decrement';
const INPUT_COUNT = "inputCount";
export default {
INCREMENT, DECREMENT, INPUT_COUNT
}
3)修改 action 对象
import types from './actionTypes.js';
export const incrementAction = () => {
return {
type: types.INCREMENT
}
}
export const decrementAction = () => {
return {
type: types.DECREMENT
}
}
export const inputCountAction = payload => {
return {
type: types.INPUT_COUNT,
payload
}
}
4)修改 reducer 文件
import types from './actionTypes.js'
// state 的初始值
const initState = 0;
const countReducer = (state = initState, action) => {
switch (action.type) {
case types.INCREMENT: return state + 1;
case types.DECREMENT: return state - 1;
case types.INPUT_COUNT: return action.payload;
default: return state;
}
}
export default countReducer;