使用1.初始化store// app.wpyimport { setstore } from 'wepy-redux'import configstore from './store'const store = configstore()setstore(store) //setstore是将store注入到所有页面中
// store文件夹下的index.jsimport { createstore, applymiddleware } from 'redux'import promisemiddleware from 'redux-promise'import rootreducer from './reducers'export default function configstore () { const store = createstore(rootreducer, applymiddleware(promisemiddleware)) //生成一个 store 对象 return store}
applymiddleware 函数的作用就是对 store.dispatch 方法进行增强和改造
这里就是使用redux-promise来解决异步
2.page里面获取storeimport { getstore } from 'wepy-redux' const store = getstore()// dispatchstore.dispatch({type: 'xx', payload: data}) //xx是reducer名字 payload就是携带的数据store.dispatch(getallhoominfo(store.getstate().base)) //xx是action名字//获取stateconst state = store.getstate()
3.连接组件@connect({ data:(state) => state.base.data //注意这里是base下的state 所有要加上base.})
文件介绍redux文件
typetypes里是触发action的函数名称 只是存储函数名字
按照模块去创建type.js
//base.jsexport const getallhomeinfo = 'getallhomeinfo'
写好了函数名称 在index.js中export出来
export * from './counter'export * from './base'
reducers随着应用变得复杂,需要对 reducer 函数 进行拆分,拆分后的每一块独立负责管理 state 的一部分
这个时候多个模块的reducer通过combinereducers合并成一个最终的 reducer 函数,
import { combinereducers } from 'redux'import base from './base'import counter from './counter'export default combinereducers({ base, counter})
模块使用handleactions 来处理reducer,将多个相关的reducers写在一起
handleactions有两个参数:第一个是多个reducers,第二个是初始state
getallhomeinfo reducer是将异步action返回的值赋值给data
//base.jsimport { handleactions } from 'redux-actions'import { getallhomeinfo } from '../types/base'const initialstate = { data: {}}export default handleactions({ [getallhomeinfo] (state, action) { return { ...state, data: action.payload } }}, initialstate)
actionsactions是对数据的处理
在index.js中export出来
export * from './counter'export * from './base'
createaction用来创建action的
import { getallhomeinfo } from '../types/base'import { createaction } from 'redux-actions'import { http, apis } from '../../libs/interface'export const getallhoominfo = createaction(getallhomeinfo, (base) => { return new promise(async resolve => { let data = await http.get({ url: apis.ls_url + apis.allhomeinfo, data: {} }) resolve(data)**//返回到reduer的action.payload** })})
用法<script> import wepy from 'wepy' import { connect } from 'wepy-redux' import { getallhoominfo } from '../store/actions/base.js'// 引入action方法 import { getstore } from 'wepy-redux' const store = getstore() @connect({ data:(state) => state.base.data }) export default class index extends wepy.page { data = { } computed = { } onload() { store.dispatch(getallhoominfo(store.getstate().base)) } }</script>
推荐教程:《微信小程序》
以上就是小程序中wepy-redux的使用以及存储全局变量的详细内容。
