推荐使用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())
![](https://img.haomeiwen.com/i15401334/99f4e4c208633ea7.png)
网友评论