需求:实施显示数据
变式:点击显示点击次数

实现

read.js
绘制DOM以及链接 couter 的 pr函数

  1. import { add, minus, asyncAdd } from '../../actions/counter'
  2. import './index.scss'
  3. @connect(({ pr }) => ({
  4. pr
  5. }), (dispatch) => ({
  6. add () {
  7. dispatch(add())
  8. },
  9. dec () {
  10. dispatch(minus())
  11. },
  12. asyncAdd () {
  13. dispatch(asyncAdd())
  14. }
  15. }))
  16. class Index extends Component {
  17. config = {
  18. navigationBarTitleText: '阅览中心'
  19. }
  20. componentWillReceiveProps (nextProps) {
  21. console.log(this.props, nextProps)
  22. }
  23. render () {
  24. return (
  25. <View className='index'>
  26. <View className='at-row'>
  27. <View className='at-col' >
  28. <Button className='add_btn' onClick={this.props.add}>座位数{this.props.pr.num}</Button>
  29. </View>
  30. </View>
  31. </View>
  32. )
  33. }
  34. }
  35. export default Index

reducers/counter.js
在reducers里面描述actions 和 store 的state关系 ,定义一个 pr 的函数,数量的初始值为0,点击一次+1
只有actions 可以改变state tree 的状态,reducers是具体怎么改变,actions大概是需要改什么(类似大纲)

  1. const INITIAL_STATE = {
  2. num: 0
  3. }
  4. export default function pr (state = INITIAL_STATE, action) {
  5. switch (action.type) {
  6. case ADD:
  7. return {
  8. ...state,
  9. num: state.num + 1
  10. }
  11. case MINUS:
  12. return {
  13. ...state,
  14. num: state.num - 1
  15. }
  16. default:
  17. return state
  18. }
  19. }

reducers/index.js
导出 reducers的 pr 函数

  1. export default combineReducers({
  2. pr
  3. })

细节注意:函数名

小程序初始状态下 pr会被定义为counter,由于 里面有多个 counter.js 文件,容易引起歧义而使得逻辑比较混乱,建议起一个其他的名字。