Redux基础知识

1.Redux:

      安装:cnpm i redux -S

    引入:import {createStore} from 'redux'

2.调用:

    创建:let store=createStore(counter)

    store:(只允许有一个)

      1.store.getState() --->获取state的值

      2.store.dispatch({type:type})--->传递参数给action

      3.store.subscribe(render) --->监听render,更改reducer里面数据之后刷新到页面

      4.store.replaceReducer()--->更换数据源

3.合并(combineReducers): 

    引入:import { combineReducers } from 'redux'

    导出:export default combineReducers ({ ...相应数据源 })

    使用:

      1.store.getState()不是单个值了,而是取出相应数据源对应的值  例子:sore.getState().counter

      2.store.dispatch()方法不受影响 ----》但是操作函数名最好不要同名--->重名的话都会执行一遍

4.store的唯一性

    1.store一旦不是唯一,就变成了各自不相通的数据了,各自为政

    2.store单拿出来,以便全局调用

      import {createStore} from 'redux'

      let store=createStore(counter)

      export default {store}

5.applyMiddleware 中间键       

    引入:import { creaapplyMiddleware } from 'redux'

    使用:let store=createStore(counter,creaapplyMiddleware(fun))

function fun({getState}){
  return function (dispatch){
    return function (action){
      console.log(action)
      dispatch(action)   //执行这个才能继续执行----不想执行,就去拦截
    }
  }
}

6. redux-thunk  可以强化dispatch 异步执行

    安装:npm i redux-thunk -S

    引用:import thunk  from 'redux-thunk'

    使用:thunk直接把dispatch变成异步   

 let store=createStore(counter,applyMiddleware(thunk,fun))
         store.dispatch(fun(dispatch){           //可以放入需要执行的函数           setTimeout(()=>{             dispatch({type:'aaa'})           },1000)          })

      

原文地址:https://www.cnblogs.com/yxkNotes/p/13518808.html