小程序框架wepy+redux的聯(lián)合開發(fā)小程序

redux基礎

在redux整體框架中,由store統(tǒng)一管理系統(tǒng)數(shù)據(jù),因此,需要先設計action,reducer,然后由reducer創(chuàng)建store。

其中:
action通過action creator函數(shù)生成,action creator函數(shù)則是一個返回包含type字段的對象。
reducer則是用于根據(jù)dispatch的action類型的生成新的state的純函數(shù)。
redux提供createStore方法接收一個reducer,返回一個store對象。該對象中包含getState,dispatch方法,用于獲取內(nèi)部狀態(tài)state和發(fā)送action。

// action Type:
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'

// action:
function increment(payload) {
  return {
    type: INCREMENT
  }
}

function decrement(payload) {
  return {
    type: DECREMENT
  }
}

// reducer:
function counter(state = 0, action) {
  switch (action.type) {
    case INCREMENT:
      return state + 1
    case DECREMENT:
      return state - 1
    default:
      return 0
  }
}

// store:
const store = createStore(combineReducers({ counter }))

// 獲取state
console.log(store.getState())

// 派發(fā)action
store.dispatch({type: 'INCREMENT'})

// 獲取更新后的state
console.log(store.getState())

以上生成整個框架中所需的store對象。

連接wepy和redux

連接react和redux之間提供了react-redux包,對外提供了Provider組件,將store傳遞到子頁面(組件)中,提供connect方法,將state和action注入到子頁面(組件)中。

對于wepy,同樣提供了wepy-redux包,對外提供setStore,getStore,以及connect方法。
setStore是將store注入到小程序的所有頁面中;
getStore用于在頁面中獲取Store對象;
connect將state和actions注入到子頁面(組件)中;

// 在app.wpy中將store注入頁面(組件中)
setStore(store)

// 在其他頁面中使用connect將頁面所需的數(shù)據(jù)注入到頁面中
<template>
  <view id="root">Hello Wepy!{{counter}}</view>
  <button @tap="increment">增加</button>
  <button @tap="decrement">減少</button>
</template>

<script>
import wepy from 'wepy'
import { connect } from 'wepy-redux'

import { increment, decrement } from '../store/actions'

@connect({ // state
  counter(state) { // 注入counter
    return state.counter
  }
},
  { // action Creator
    increment, 
    decrement
  })

export default class Index extends wepy.page {

}
</script>

注意:使用connect方法將states和actions注入到頁面(組件)中時,是將states注入到小程序的computed屬性中,將actions注入到methods屬性中,在js邏輯中可以通過this.XXX和this.methods.XXX獲取注入的state和action。

wepy-redux地址:https://www.npmjs.com/package/wepy-redux

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容