微信小程式Redux綁定執行個體詳解,小程式redux

來源:互聯網
上載者:User

小程式Redux綁定執行個體詳解,小程式redux

小程式Redux綁定執行個體詳解

安裝

clone或者下載程式碼程式庫到本地:

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

將dist/wechat-weapp-redux.js(或者拷貝minify的也可以)檔案直接拷貝到小程式的工程中,例如(下面假設我們把第三方包都安裝在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的實現只是簡單的將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定義的資料了。

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

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.