美文网首页
redux构建store模板目录,合并多个reducer

redux构建store模板目录,合并多个reducer

作者: 小小的开发人员 | 来源:发表于2019-05-31 11:34 被阅读0次

推荐使用redux构建store时用以下目录结构

.
├── action
│   ├── actionCreator.js
│   └── actionTypes.js
├── index.js
└── reducer
    ├── add
    │   └── index.js
    ├── index.js
    └── square
        └── index.js

action / actionTypes.js,action的type管理器

export const ADD = 'add'
export const SQUARE = 'square'

action / actionCreator.js,action生成器

export default function actionCreator (type, value = null) {
    return {type, value}
}

reducer / add / index.js,子reducer

// 建议reducer使用这种结构
import { ADD } from '../../action/actionTypes'

// 1.定义默认数据
const initialState = {
    a: 1
}

// 2.Reducer
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case ADD:
            return { ...state, a: state.a + action.value }
        default:
            return state
    }
}
// 3.导出
export default reducer

reducer / square / index.js,另一个子reducer

// 建议reducer使用这种结构
import { SQUARE } from '../../action/actionTypes'

// 1.定义默认数据
const initialState = {
    a: 1
}

// 2.Reducer
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case SQUARE:
            return { ...state, a: action.value * action.value }
        default:
            return state
    }
}
// 3.导出
export default reducer

reducer / index,合并多个子reducer

import add from './add'
import square from './square'
import { combineReducers } from 'redux'

const reducers = combineReducers ({
    add,
    square
})
export default reducers

index.js,构建store

import { createStore } from 'redux'
import reducer from './reducer'

const store = createStore(reducer)

export default store

好了,我们写个测试文件

import actionCreator from './action/actionCreator';
import {ADD, SQUARE} from './action/actionTypes';
import store from './index'

let action = actionCreator(ADD, 12)
store.dispatch(action)
console.log(store.getState())
let action2 = actionCreator(SQUARE, 2)
store.dispatch(action2)
console.log(store.getState())

相关文章

网友评论

      本文标题:redux构建store模板目录,合并多个reducer

      本文链接:https://www.haomeiwen.com/subject/nbrwtctx.html