wepy-redux

wepy-redux

redux文件
clipboard.pngredux

  • type

types裏是觸發action的函數名稱 只是存儲函數名字異步

按照模塊去建立type.jsasync

clipboard.png

//base.js
export const GETALLHOMEINFO = 'GETALLHOMEINFO'

寫好了函數名稱 在index.js中export出來函數

export * from './counter'
export * from './base'
  • reducers

隨着應用變得複雜,須要對 reducer 函數 進行拆分,拆分後的每一塊獨立負責管理 state 的一部分
這個時候多個模塊的reducer經過combineReducers合併成一個最終的 reducer 函數,url

clipboard.png

import { combineReducers } from 'redux'
import base from './base'
import counter from './counter'

export default combineReducers({
  base,
  counter
})

模塊使用handleActions 來處理reducer,將多個相關的reducers寫在一塊兒
handleActions有兩個參數:第一個是多個reducers,第二個是初始statespa

GETALLHOMEINFO reducer是將異步action返回的值賦值給datacode

//base.js
import { handleActions } from 'redux-actions'
import { GETALLHOMEINFO } from '../types/base'

const initialState = {
  data: {}
}
export default handleActions({
  [GETALLHOMEINFO] (state, action) {
    return {
      ...state,
      data: action.payload
    }
  }
}, initialState)
  • actions

actions是對數據的處理
clipboard.png
在index.js中export出來ip

export * from './counter'
export * from './base'

createAction用來建立Action的get

import { GETALLHOMEINFO } from '../types/base'
import { createAction } from 'redux-actions'
import { Http, Apis } from '../../libs/interface'

export const getAllHoomInfo = createAction(GETALLHOMEINFO, (base) => {
  return new Promise(async resolve => {
    let data = await Http.get({
      url: Apis.ls_url + Apis.allHomeInfo,
      data: {}
    })
    resolve(data)//返回到reduer的action.payload
  })
})
  • 用法
<script>
  import wepy from 'wepy'
  import { connect } from 'wepy-redux'
  import { getAllHoomInfo } from '../store/actions/base.js'// 引入action方法
  import { getStore } from 'wepy-redux'
 
  const store = getStore()
  
  @connect({
    data(state) {
      return state.base.data //注意這裏是base下的state 全部要加上base.
    }
  }, {
    getAllHoomInfo
  })

  export default class Index extends wepy.page {
    data = {
    }

    computed = {
    }

    onLoad() {
      store.dispatch(getAllHoomInfo(store.getState().base))
    }
    
  }
</script>
本站公眾號
   歡迎關注本站公眾號,獲取更多信息