简单案例-点击按钮数字+1
1.找到根标签,使用Provider进行包裹并传递全局store
import { Provider } from 'react-redux';
import store from '@/store';
public render = () => {
const { children } = this.props;
return
<Provider store={store}>{children}</Provider>;
};
注意:此处里面不能直接包裹组件,必须配备路由。否则会出现如下错误
Type '{}' is missing the following properties from type...
此处应修改为:
或如顶上代码所示在route.ts中配置子路由。
2.models
import * as util from './util';
export const start = {
state: {
count: 0,
} as util.IStart,
reducers: {
changeCount: (state: util.IStart, count: number) => {
return {
count,
};
},
},
effects: {},
};
其中,
state为存放模块状态的地方,reducers为改变state状态的地方,每个reducers函数都会返回一个对象作为模块最新的state,reducers中的函数必须为同步函数;
effects处理异步函数。
3.models->util限制start中state的类型
export interface IStart {
count: number;
}
4.在store中初始化models
import { init, RematchDispatch, RematchRootState } from '@rematch/core';
import * as models from './models';
const store = init({
models,
});
export type Store = typeof store;
export type Dispatch = typeof store.dispatch;
export type iRootState = RematchRootState<typeof models>;
export default store;
5.使用
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Dispatch, iRootState } from '@/store';
const mapState = (state: iRootState) => ({
start: state.start,
});
const mapDispatch = (dispatch: Dispatch) => ({
changeCount: (val: number) => dispatch.start.changeCount(val),
});
type connected = ReturnType<typeof mapState> & ReturnType<typeof mapDispatch>;
namespace AddSpace {
export interface IProps extends connected {}
}
class Add extends Component<AddSpace.IProps> {
constructor(props: AddSpace.IProps) {
super(props);
}
public render = () => {
const { start, changeCount } = this.props;
return (
<button
onClick={() => {
changeCount(start.count + 1);
}}
>
点我+1
</button>
);
};
}
export default connect(mapState, mapDispatch as Dispatch)(Add);