您好,欢迎来到年旅网。
搜索
您的当前位置:首页Remath完整使用流程-简单案例

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...

此处应修改为:

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->utilstart中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);

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- oldu.cn 版权所有 浙ICP备2024123271号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务