8.1 redux (简写版,完整版,异步版)

零.不用redux方法:

目录:src:

component:

  count:   //reducers 每一个组件都得有一个reducers。

     index.jsx//(store只有一个。)

this,setState({count: count+value*1 } ) // 上面的value是字符串,*1 强制类型转换!+也是强制转换。

一  mini版:

2 个文件。

3 个API。

src:
  count:
    index.jsx   component:     count_redux: count_reducer.js
//reducers 每一个组件都得有一个reducers。     store.js //(store只有一个。)

store.js专门用于创建store: createStore(reducer),

// 下面代码 就是暴露store对象,整个应用只有一个store对象
import { createStore} from ‘redux’
import countReducer from './count_redcuer'
//引入为count组件服务的。分别暴露/统一暴露。一般默认暴露。
export default createStore(
countReducer )。

count_redux.js 改文件就是创建一个count服务的reducer,reducer的本质就是一个函数。

函数接受两个参数,一个是之前的状态(preState),一个是动作对象(action)

function c(preStae,action){

  if (preState == undefined) preState = 0 //初始化的时候
  const {type ,data} = action //从action对象中获取type,data

  switch(type) {//根据type决定什么时候加工。

case 'increament':return  prestate +data //+的时候
case 'decreament':return prestate -data //-的时候

default: preState//初始化的时候

  }

}

还有一种写法:

const initState = 0 //方便管理
export fault function
countReducer(preStae=initState ,action)
{   

    const {type ,data} = action //从action对象中获取type,data   

    switch(type) {//根据type决定什么时候加工。

      case 'increament':return prestate +data //+的时候

      case 'decreament':return prestate -data //-的时候

      default: preState//初始化的时候   
  }
}

this.state.count.不能找自己家的值。

找到store

import store from ../../redux/store

引入store用于获取redux中的状态。

child :节点

store.getState()

{{ store.getState }}

increment = () =>{ consot {value ] =this.selectment   store.dispathj{ type:' '  ,  data:value*1  } } 

type: undifined,随机的数值。 

data:  

如果redux 调用render:

componentDidMount(){ //只要redux状态变换。旧调用

store.subscribe( () =>{  this.setState({}) })} 调用render。 this.render(); 

二。完成版::::

需要加上 文件:action creators.js

count_action_creator.js 改文件专门为count组件生成action对象。

export function createIncrementAction (data) { return { type: 'increment',data} }

export function createDecrementAction (data) { return { type: 'decrement',data} }

//export分别暴露

{createIncreatemenAction((value*1), createDecreamentAction(value*1) }  //引入。

需要加上文件:constant.js 定义action对象中type类型的常量值。目的:便于管理,防止单词写错。

constant.js:  暴露 export const INCREMENT = 'increment'
count_action.js:引入 import {INCREMNET,DECREMNET} from './constant'

三 异步案例:

延迟的动作不想交给组件自身,想交给action。不想把等待的时间 放在自身组件上。而是想 放在action上面。

= (data,time)= { return () => { } }

//异步函数

同步action: action的值就是object类型的一般对象。

异步action:action的值就是函数: export const createIncrementAsyncAction( data,time )= >{ return ()=>{}} 

函数里面式:异步函数。 store.dispatch( {type:INCREAMENT,data})

            store,dispatch( { } )

plain ojbect.

一般。 object ,function函数。 store不允许这么做! 交给store! reducres。store。

yarn add redux-thunk  (thunk 形式转换程序)

store from './store'

 store 在组件。 store.getState获取。  store.dispatch ()分发给

原文地址:https://www.cnblogs.com/hacker-caomei/p/14389719.html