Remath完整使用流程-简单案例

简单案例-点击按钮数字+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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值