项目作者: charleyw

项目描述 :
微信小程序Redux绑定
高级语言: JavaScript
项目地址: git://github.com/charleyw/wechat-weapp-redux.git
创建时间: 2016-09-29T07:18:23Z
项目社区:https://github.com/charleyw/wechat-weapp-redux

开源协议:

下载


微信小程序Redux绑定

用于在微信小程序为页面绑定Redux Store。

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

安装

  1. clone或者下载代码库到本地:

    1. git clone https://github.com/charleyw/wechat-weapp-redux
  2. dist/wechat-weapp-redux.js(或者拷贝minify的也可以)文件直接拷贝到小程序的工程中,例如(下面假设我们把第三方包都安装在libs目录下):

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

    上面的命令将包拷贝到小程序的libs目录下

使用

  1. 将Redux Store绑定到App上。

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

    Provider是用来把Redux的store绑定到App上。

    1. App(Provider(store)({
    2. onLaunch: function () {
    3. console.log("onLaunch")
    4. }
    5. }))

    provider的实现只是简单的将store加到App这个global对象上,方便在页面中用getApp取出来

    上面这段代码等同于:

    1. App({
    2. onLaunch: function() {
    3. console.log( "onLaunch" )
    4. },
    5. store: store
    6. })
  2. 在页面的定义上使用connect,绑定redux store到页面上。

    1. const pageConfig = {
    2. data: {
    3. },
    4. ...
    5. }

    页面的定义

    1. const mapStateToData = state => ({
    2. todos: state.todos,
    3. visibilityFilter: state.visibilityFilter
    4. })

    定义要映射哪些state到页面

    1. const mapDispatchToPage = dispatch => ({
    2. setVisibilityFilter: filter => dispatch(setVisibilityFilter(filter)),
    3. toggleTodo: id => dispatch(toggleTodo(id)),
    4. addTodo: text => dispatch(addTodo(text)),
    5. })

    定义要映射哪些方法到页面

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

    使用connect将上述定义添加到pageConfig中。

    1. Page(nextPageConfig);

    注册小程序的页面

  3. 说明

    完成上述两步之后,你就可以在this.data中访问你在mapStateToData定义的数据了。

    mapDispatchToPage定义的action会被映射到this对象上。

Example

详细的使用例子可以参照: wechat-weapp-redux-todos

真机实测版请clone下面这个repo,用小程序开发工具开启预览:

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