redux核心分为action、reducer、store三大模块
action定义公共变量、action构建函数
reducer定义当action来的时候如何改变state
store初始化存储空间,从redux引入createStore函数,并将reducer传入
通过store.dispatch来修改store,store.subscribe来监听redux的变化,进而通过callback来定义做出什么处理
const redux = require('redux')
// action
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
const ADD_NUMBER = 'ADD_NUMBER'
const SUB_NUMBER = 'SUB_NUMBER'
const addAction = (num) => ({
type: ADD_NUMBER,
num,
})
const subAction = (num) => ({
type: SUB_NUMBER,
num
})
export const decAction = () => ({
type: DECREMENT
})
export const incAction = () => ({
type: INCREMENT
})
// reducer
const initialState = {
counter: 0
}
const reducer = (state = initialState, action) => {
switch(action.type) {
case INCREMENT:
return {...state, counter: state.counter + 1}
case DECREMENT:
return {...state, counter: state.counter - 1}
case ADD_NUMBER:
return {...state, counter: state.counter + action.number}
case SUB_NUMBER:
return {...state, counter: state.counter - action.number}
default:
return state;
}
}
// store
const store = redux.createStore(reducer)
store.subscribe(() => {
console.log('state发生了改变', store.getState().counter)
})
store.dispatch(addAction(1))
store.dispatch(subAction(2))
store.dispatch(decAction())
store.dispatch(incAction(2))