状态管理神器 moox 发布 1.0 beta版本

moox

moox 是基于 redux 开发的高性能状态管理机。react

github: github.com/suxiaoxin/m…git

我是开源项目 YApi 做者,moox 是本身在使用 redux 过程当中生成的灵感,麻烦各位 star 下github。github

安装

npm install mooxnpm

用法

moox 封装了 redux 的 action, reducer 到一个文件。redux

首先调用 moox(models) 初始化,models 对象结构是api

{
    modelName: model
}
复制代码

model 结构以下面示例代码,model.state 是初始化的 state, 带 Action 字符串后缀的函数是一个 action,比较特殊的是,action 函数不须要写繁琐的 type, 全部 actionType 都会自动生成。bash

model.reducers 存储纯函数 reducer,跟 redux-reducer 不同的是 moox-reducer 不须要返回新的 state,直接修改函数参数传入的 state,便可自动化生成新的 state。dom

详细用法请参考 demo 下的 index.js函数

Example

model 层代码:性能

const model = {
  state: {
    list: [1],
    status: 0
  },
  requestStatusAction: () => { },
  addUserAction: () => (
    {
      payload: new Promise((resolve) => {
        setTimeout(function () {
          resolve(100)
        }, 1000)
      })
    }),  
  reducers: {
    addUserAction: function (state, action) {
      state.list.push(Math.round(Math.random() * 1000))
      state.status = 0
    },
    requestStatusAction: function (state, action) {
      state.status = 1
    }
  }
}

复制代码

组件层跟 react-redux 用法同样:

const App = (props)=>{  
  const handleClick = () =>{
    if(props.user.status === 1) return;
    props.requestStatusAction()    
    props.addUserAction()  
  }

  return <div> <div><button onClick={handleClick}>Add Random Number</button> {props.user.status === 1? 'loading...' : ''} </div> {props.user.list.map((item, index)=>{ return <div key={index}>{item}</div> })} </div>
}


export default connect((state)=>({
  user: state.user
}), {
  addUserAction: Model.user.addUserAction,
  requestStatusAction: Model.user.requestStatusAction
})(App)

复制代码
相关文章
相关标签/搜索