redux应用加减求和功能怎么实现

2023-06-14

本篇内容介绍了“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'))  

})

“redux应用加减求和功能怎么实现”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注本站网站,小编将为大家输出更多高质量的实用文章!

《redux应用加减求和功能怎么实现.doc》

下载本文的Word格式文档,以方便收藏与打印。