小程序模板網(wǎng)

微信小程序Redux綁定 – wechat-weapp-redux

發(fā)布時(shí)間:2018-04-20 10:40 所屬欄目:小程序開發(fā)教程

用于在微信小程序?yàn)轫?yè)面綁定Redux Store。

PS: 代碼是基于react-redux修改的

安裝

  1. clone或者下載代碼庫(kù)到本地:

    git clone https://github.com/charleyw/wechat-weapp-redux
  2. 將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)只是簡(jiǎn)單的將store加到App這個(gè)global對(duì)象上,方便在頁(yè)面中用getApp取出來

    上面這段代碼等同于:

    App({
      onLaunch: function() {
          console.log( "onLaunch" )
        },
        store: store
    })
  2. 在頁(yè)面的定義上使用connect,綁定redux store到頁(yè)面上。

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

    頁(yè)面的定義

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

    定義要映射哪些state到頁(yè)面

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

    定義要映射哪些方法到頁(yè)面

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

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

    Page(nextPageConfig);

    注冊(cè)小程序的頁(yè)面

  3. 說明

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

    mapDispatchToPage定義的action會(huì)被映射到this對(duì)象上。

Example

詳細(xì)的使用例子可以參照: wechat-weapp-redux-todos

真機(jī)實(shí)測(cè)版請(qǐng)clone下面這個(gè)repo,用小程序開發(fā)工具開啟預(yù)覽:

git clone -b release https://github.com/charleyw/wechat-weapp-redux-todos.gi


本文地址:http://m.u-renovate.com/wxmini/doc/course/23757.html 復(fù)制鏈接 如需定制請(qǐng)聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢
AI智能客服 ×