Redux拆分(React)

一、创建目录

在这里插入图片描述

二、拆分 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;
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值