欢迎来到DIVCSS5查找CSS资料与学习DIV CSS布局技术!
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'))  
 
})

如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64207.shtml