Redux 学习系列(二) —— 实现一个计数器

目录结构:

src |
   -| App.js
   -| index.css
   -| index.js
   views |
     commponents |
       count |
            -| index.jsx
   redux | 
         actions |
                -| count.js
         reducers |
                 -| count.js
         store |
              -| index.js
         -| Constans.js

创建一个 redux 文件夹,分别创建以下文件:

views/redux/store/index.js

/* 
	用于暴露一个store对象,整个应用只有一个store对象
*/

// 引入createStore,专门用于创建redux中最为核心的store对象
import {
    createStore } from 'redux'
//引入为Count组件服务的reducer
import countReducer from '../reducers/count'
const store = createStore(countReducer)
//暴露store
export default store

views/redux/Constans.js

/**
  定义action对象中type类型的常量值:便于管理的同时防止程序员单词写错
 */
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

views/redux/reducers/count.js

/* 
  1.创建一个为Count组件服务的reducer,reducer的本质就是一个函数
  2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
import {
    INCREMENT, DECREMENT } from '../Constants'

const initState = 0 //初始化状态
export default function countReducer (preState = initState, action) {
   
  // console.log(preState);
  // 从action对象中获取:type、data
  const {
    type, data } = action
  // 根据type决定如何加工数据
  switch (type) {
   
    case INCREMENT: //如果是加
      return preState + data
    case DECREMENT: //若果是减
      return preState - data
    default:
      return preState
  }
}

views/redux/actions/count.js

/**
  为Count组件生成action对象
*/
import {
    INCREMENT,
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值