正常你定义action肯定要定义一些常量,这个常量是干什么用的呢?因为reducer要根据action.type来修改state并且actionCreators要根据这个来创建action,在多个地方共有某个东西最好在constant来初始化。这里主要初始化了如下四个:
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const ADD_NUMBER = 'ADD_NUMBER'
export const SUB_NUMBER = 'SUB_NUMBER'
之后为了你的action创建变得模板化,你需要定义actionCreators,这些actionCreators呢又引用了上面的constants:
import {
ADD_NUMBER,
SUB_NUMBER,
INCREMENT,
DECREMENT,
} from './constant'
export const addAction = num => ({
type: ADD_NUMBER,
num,
})
export const subAction = num => ({
type: SUB_NUMBER,
num
})
export const incAction = () => ({
type: INCREMENT
})
export const decAction = () => ({
type: DECREMENT
})
这里创建了一个简单的界面,即
点击+1触发store.dispatch(incAction())
点击-1触发store.dispatch(decAction())
点击+5出发store.dispatch(addAction(5))
点击-5触发store.dispatch(subAction(5))
整个流程就是点击+1->触发dispatch->reducers来进行处理->更新state。
但是问题是现在点击按钮并没有发生变化,原因是并没有监听变化,因此其实需要在页面中定义store.subscribe()来监听变化,之后来对页面进行重新渲染,返回jsx,然后react再根据diff算法来修改界面。
那么在什么生命周期中来做监听呢?答案是componentDidMount,在页面首次渲染完成后来做监听,当发生变化后,触发this.setState({counter: store.getState().counter})来重新渲染界面