作者:cat6572325,来自原文地址
const store = createStore(combineReducers(reducer)) 流程图如下:
redux可以存储程序的所有数据,通过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必须在程序里只能有一个,所以可以把它的创建写在一个项目全局方法 app.js
里面方便调用。 subscribe 它在小程序里是这样使用的 onLoad: function (options) { this.unsubscribe = store.subscribe(() => { // 当state改变时触发 this.setData(store.getState().home_reducer) //setData()为专门设置page 的 data用的,它这句的意思是获取state的数据 console.log(store.getState().home_reducer) }) //app.field_onload() }
这样就完成了绑定redux到项目 - 创建action - 创建reducer - 获取state数据并设置给page的这么一个流程。 var reducer = require('./reducer/index') //引入reducer const {createStore, combineReducers, applyMiddleware} = require('libs/redux.js') //引入redux接口 const store = createStore(combineReducers(reducer)) //创建store App({ store }) // 绑定到全局的app.js reducer结构: 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(() => { // 当state改变时触发 this.setData(store.getState().home_reducer) //setData()为专门设置page 的 data用的,它这句的意思是获取state的数据 console.log(store.getState().home_reducer) }) }, // 一个按钮的点击事件响应方法 on_button_click: function(){ store.dispatch({ type: 'CHANGE_TEXT' , text: '二' }) ; }, // 你还需要在页面退出的时候关闭这个监听 unOnLoad: function(){ this.unsubscribe() } } |