rematch的基本用法
rematch是对redux的二次封装,简化了redux是使用,极大的提高了开发体验。rematch仅仅是对redux的封装,没有依赖redux-saga,也没有关联react,因此其可以用在其他的视图库中,如vue等。
1. rematch的优点
1.省略了action types
不必再多次写字符串,使用model/method代替
2.省略了action creators
直接调用方法,不必再生产action type,使用dispatch.model.method代替
3.省略了switch语句
调用model.method方法,不必判断action type
4.集中书写状态,同步和异步方法
在一个model中使用state,reducers和effects来写状态,同步和异步方法
2. rematch的model
model中直接写state,reducers,effects,十分集中方便
export const count = { state: 0, // initial state reducers: { // handle state changes with pure functions increment(state, payload) { return state + payload } }, effects: (dispatch) => ({ // handle state changes with impure functions. // use async/await for async actions async incrementAsync(payload, rootState) { await new Promise(resolve => setTimeout(resolve, 1000)) dispatch.count.increment(payload) } }) }
3. rematch的dispatch
dispatch可以直接调用同步和异步方法,不必再发送action
import { init } from '@rematch/core' import * as models from './models' const store = init({ models, }) export const { dispatch } = store // state = { count: 0 } // reducers dispatch({ type: 'count/increment', payload: 1 }) // state = { count: 1 } dispatch.count.increment(1) // state = { count: 2 } // effects dispatch({ type: 'count/incrementAsync', payload: 1 }) // state = { count: 3 } after delay dispatch.count.incrementAsync(1) // state = { count: 4 } after delay
4. rematch的状态派发
依然使用redux的connect,mapStateToProps,mapStateToDispatch来派发状态和方法到子组件
import React from 'react' import ReactDOM from 'react-dom' import { Provider, connect } from 'react-redux' import store from './index' const Count = props => ( <div> The count is {props.count} <button onClick={props.increment}>increment</button> <button onClick={props.incrementAsync}>incrementAsync</button> </div> ) const mapState = state => ({ count: state.count }) const mapDispatch = ({ count: { increment, incrementAsync }}) => ({ increment: () => increment(1), incrementAsync: () => incrementAsync(1) }) const CountContainer = connect(mapState, mapDispatch)(Count) ReactDOM.render( <Provider store={store}> <CountContainer /> </Provider>, document.getElementById('root') )
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析