微信小程序Redux綁定實(shí)例詳解
微信小程序Redux綁定實(shí)例詳解
安裝
clone或者下載代碼庫(kù)到本地:
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是用來(lái)把Redux的store綁定到App上。
App(Provider(store)({
onLaunch: function () {
console.log("onLaunch")
}
}))
provider的實(shí)現(xiàn)只是簡(jiǎn)單的將store加到App這個(gè)global對(duì)象上,方便在頁(yè)面中用getApp取出來(lái)
上面這段代碼等同于:
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.說(shuō)明
完成上述兩步之后,你就可以在this.data中訪問(wèn)你在mapStateToData定義的數(shù)據(jù)了。
mapDispatchToPage定義的action會(huì)被映射到this對(duì)象上。
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
相關(guān)文章
關(guān)于JavaScript輪播圖的實(shí)現(xiàn)
這篇文章主要介紹了關(guān)于JavaScript輪播圖的實(shí)現(xiàn),下面文章主要是利用利用html 和 css 代碼實(shí)現(xiàn)輪播圖,詳細(xì)內(nèi)容請(qǐng)參考下面詳細(xì)內(nèi)容,希望對(duì)你有所幫助2021-11-11
微信小程序頁(yè)面開(kāi)發(fā)注意事項(xiàng)整理
這篇文章主要介紹了微信小程序頁(yè)面開(kāi)發(fā)注意事項(xiàng)整理的相關(guān)資料,需要的朋友可以參考下2017-05-05
ECMAScript?6數(shù)組的擴(kuò)展實(shí)例詳解
這篇文章主要為大家介紹了ECMAScript?6數(shù)組的擴(kuò)展實(shí)例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
實(shí)現(xiàn)微信小程序的wxml文件和wxss文件在webstrom的支持
這篇文章主要介紹了實(shí)現(xiàn)微信小程序的wxml文件和wxss文件在webstrom的支持的相關(guān)資料,需要的朋友可以參考下2017-06-06

