溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

微信小程序中Redux怎么綁定

發(fā)布時間:2022-04-19 15:43:57 來源:億速云 閱讀:250 作者:iii 欄目:開發(fā)技術(shù)

這篇“微信小程序中Redux怎么綁定”文章的知識點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“微信小程序中Redux怎么綁定”文章吧。

安裝

clone或者下載代碼庫到本地:

git clone https://github.com/charleyw/wechat-weapp-redux

將dist/wechat-weapp-redux.js(或者拷貝minify的也可以)文件直接拷貝到小程序的工程中,例如(下面假設(shè)我們把第三方包都安裝在libs目錄下):

cd wechat-weapp-redux
 cp -r dist/wechat-weapp-redux.js <小程序根目錄>/libs

上面的命令將包拷貝到小程序的libs目錄下

使用

1.將Redux Store綁定到App上。

const store = createStore(reducer) // redux store
 
 const WeAppRedux = require('./libs/wechat-weapp-redux/index.js');
 const {Provider} = WeAppRedux;

Provider是用來把Redux的store綁定到App上。

App(Provider(store)({
 onLaunch: function () {
  console.log("onLaunch")
 }
}))

provider的實(shí)現(xiàn)只是簡單的將store加到App這個global對象上,方便在頁面中用getApp取出來

上面這段代碼等同于:

App({
 onLaunch: function() {
   console.log( "onLaunch" )
  },
  store: store
})

2.在頁面的定義上使用connect,綁定redux store到頁面上。

const pageConfig = {
  data: {
  },
  ...
 }

頁面的定義

const mapStateToData = state => ({
  todos: state.todos,
  visibilityFilter: state.visibilityFilter
 })

定義要映射哪些state到頁面

const mapDispatchToPage = dispatch => ({
  setVisibilityFilter: filter => dispatch(setVisibilityFilter(filter)),
  toggleTodo: id => dispatch(toggleTodo(id)),
  addTodo: text => dispatch(addTodo(text)),
 })

定義要映射哪些方法到頁面

const nextPageConfig = connect(mapStateToData, mapDispatchToPage)(pageConfig)

使用connect將上述定義添加到pageConfig中。

Page(nextPageConfig);

注冊小程序的頁面

3.說明

完成上述兩步之后,你就可以在this.data中訪問你在mapStateToData定義的數(shù)據(jù)了。

mapDispatchToPage定義的action會被映射到this對象上。

以上就是關(guān)于“微信小程序中Redux怎么綁定”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI