0
点赞
收藏
分享

微信扫一扫

Redux拆分

醉东枫 2022-02-12 阅读 56

一、创建目录

在这里插入图片描述

二、拆分 reducer

1)创建 reducer
// state 的初始值
const initState = 0;

const countReducer = (state = initState, { type, payload }) => {
    switch (type) {
        default: return state;
    }
}
export default countReducer;
2)合并 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 值
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;
举报

相关推荐

0 条评论