|
作者:cat6572325,來自原文地址
const store = createStore(combineReducers(reducer)) 流程圖如下:
redux可以存儲程序的所有數(shù)據(jù),通過getState()就能獲取。
dispatch({type: CHANGE_TEXT,data: '二'});
但是這樣還不能把它存儲進redux的state里面,更別說顯示了。
home_reducer(state,action)
{
switch(action.type)
{
case CHANGE_TEXT:
retuen Object.assgin({},state,{data: action.data})
}
}
這樣就可以存進state里面。 store.getState().home_reducer 這里的store必須在程序里只能有一個,所以可以把它的創(chuàng)建寫在一個項目全局方法 app.js
里面方便調(diào)用。 subscribe 它在小程序里是這樣使用的
onLoad: function (options) {
this.unsubscribe = store.subscribe(() => { // 當(dāng)state改變時觸發(fā)
this.setData(store.getState().home_reducer) //setData()為專門設(shè)置page 的 data用的,它這句的意思是獲取state的數(shù)據(jù)
console.log(store.getState().home_reducer)
})
//app.field_onload()
}
這樣就完成了綁定redux到項目 - 創(chuàng)建action - 創(chuàng)建reducer - 獲取state數(shù)據(jù)并設(shè)置給page的這么一個流程。
var reducer = require('./reducer/index') //引入reducer
const {createStore, combineReducers, applyMiddleware} = require('libs/redux.js') //引入redux接口
const store = createStore(combineReducers(reducer)) //創(chuàng)建store
App({
store
}) // 綁定到全局的app.js
reducer結(jié)構(gòu):
var home_reducer= require('./field/reducer') // reducer
module.exports = {home_reducer} // 可以引用多個reducer
home_reducer文件:
var data = {
text: '一'
}
function home_reducer(state, action) {
if (state == undefined)
return data
switch (action.type) {
case CHANGE_TEXT:
return Object.assgin({},state,{text: action.text});
default: return state
}
}
homePage.js:
var store = getApp().store
onLoad: function (options) {
this.unsubscribe = store.subscribe(() => { // 當(dāng)state改變時觸發(fā)
this.setData(store.getState().home_reducer) //setData()為專門設(shè)置page 的 data用的,它這句的意思是獲取state的數(shù)據(jù)
console.log(store.getState().home_reducer)
})
},
// 一個按鈕的點擊事件響應(yīng)方法
on_button_click: function(){
store.dispatch({ type: 'CHANGE_TEXT' , text: '二' }) ;
},
// 你還需要在頁面退出的時候關(guān)閉這個監(jiān)聽
unOnLoad: function(){
this.unsubscribe()
}
}
|