Rematch is Redux best practices without the boilerplate. No more action types, action creators, switch statements or thunks. See a comparison.
npm install @rematch/core
init configures your reducers, devtools & store.
import { init } from '@rematch/core'
import * as models from './models'
const store = init({
models,
plugins: [],
})
For additional setup, pass in a configuration or one of many existing plugins.
The model brings together state, reducers, async actions & action creators in one place.
export const count = {
state: 0, // initial state
reducers: { // state changes with pure functions
addBy: (state, payload) => state + payload,
},
effects: { // state changes with impure functions
async addByAsync(payload, state) {
await Promise.resolve()
this.addBy(payload)
}
}
}
Understanding models is as simple as answering a few questions:
dispatch is how we trigger reducers & effects in your models. Dispatch standardizes your actions without the need for action types, action creators, or mapDispatchToProps.
import { dispatch } from '@rematch/core'
// state = { count: 0 }
// reducers
dispatch({ type: 'count/addBy', payload: 1 }) // state = { count: 1 }
dispatch.count.addBy(1) // state = { count: 2 }
// effects
dispatch({ type: 'count/addBy', payload: 1 }) // state = { count: 3 } after delay
dispatch.count.addByAsync(1) // state = { count: 4 } after delay
Dispatch can be called directly, or with the dispatch.model.action(payload)
shorthand.
React | Vue | AngularJS | Angular 2
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider, connect } from 'react-redux'
import { init, dispatch } from '@rematch/core'
import * as models from './models'
const store = init({
models,
})
const Count = props => (
<div>
<h1>The count is: {props.count}</h1>
<button onClick={props.addByOne}>Add 1</button>
<button onClick={props.addByOneAsync}>Add 1 Async</button>
</div>
)
const CountContainer = connect(state => ({
count: state.count,
addByOne: () => dispatch.count.addBy(1),
addByOneAsync: () => dispatch.count.addByAsync(1)
}))(Count)
ReactDOM.render(
<Provider store={store}>
<CountContainer />
</Provider>,
document.getElementById('root')
)
See the API Reference.
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。