redux应用加减求和功能demo

6 篇文章 0 订阅
5 篇文章 1 订阅

redux工作原理图
在这里插入图片描述

1.去除Count组件自身的状态count组件为我们需要使用的求和组件
2.src下建立redux文件,redux内部创建store以及reducer等等:

-redux

					-store.js
					-count_reducer.js
					-count_action.js
					-constant.js 

3.store.js文件中:
1).引入redux中的createStore函数,创建一个store
2).createStore调用时要传入一个为其服务的reducer
3).记得暴露store对象

/*
该文件专门用于暴露一个store对象,整个应用只有一个store对象
*/

//1.引入createStore,专门用于创建redux中最为核心的store对象
import { createStore } from "redux";
//2.引入为count组件服务的reducer
import countReducer from './count_reducer'

export default createStore(countReducer)

4.constant.js 放置容易写错的type值

//约定常量类型
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'

5.count_action.js 专门用于创建action对象

/*
该文件专门为count组件生成action对象
*/
export const cteateIncrementActon = data => ({type:'increment',data})
export const cteateDecrementActon = data => ({type:'decrement',data})

6.count_reducer.js文件中:
1).reducer的本质是一个函数,接收:preState,action,返回加工后的状态
2).reducer有两个作用:初始化状态,加工状态
3).reducer被第一次调用时,是store自动触发的,
传递的preState是undefined,
传递的action是:{type:’@@REDUX/INIT_a.2.b.4}

/*

该文件时用于创建一个为count组件服务的reducer,reducer的本质就是一个函数

reducer函数会接到两个参数,分别为之前的状态(preState),动作对象(action)
*/
import {INCREMENT,DECREMENT} from './constant'

const initState = 0
export default function countReducer(preState=initState,action){
    //拿到两个值(要干嘛,数据)
    //从action对象中获取:type,data
    const {type,data} = action
    // if(preState === undefined) preState = 0
    //根据type决定如何加工数据
    switch (type){
        case INCREMENT: //如果是加
          return  preState + data 
        case DECREMENT: //如果是减
          return  preState - data 
        default:
        return preState;
    }
}

7.在index.js中监测store中状态的改变,一旦发生改变重新渲染
App

import React from 'react'
import ReactDom from 'react-dom'
import App from './App'
import store from './redux/store'

ReactDom.render(<App />,document.getElementById('root'))

store.subscribe(()=>{
    ReactDom.render(<App />,document.getElementById('root'))  
})
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值