rematch的基本用法

rematch的基本用法rematch 是对 redux 的二次封装 简化了 redux 是使用 极大的提高了开发体验 rematch 仅仅是对 redux 的封装 没有依赖 redux saga 也没有关联 react 因此其可以用在其他的视图库中 如 vue 等 1 rematch 的优点 1 省略了 actiontypes 不必再多次写字符串 使用 model method 代替 2 省略了 actioncreato

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 => (  
   
The count is {props.count}
) 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( , document.getElementById('root') )

 

转载于:https://www.cnblogs.com/mengff/p/9510264.html

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/222275.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 下午4:09
下一篇 2026年3月17日 下午4:10


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号