新西兰服务器

微信小程序中Redux怎么绑定


微信小程序中Redux怎么绑定

发布时间:2022-04-19 15:43:57 来源:高防服务器网 阅读:85 作者:iii 栏目:开发技术

这篇“微信小程序中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对象上。

以上就是关于“微信小程序中Redux怎么绑定”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注高防服务器网行业资讯频道。

[微信提示:高防服务器能助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。

[图文来源于网络,不代表本站立场,如有侵权,请联系高防服务器网删除]
[