ts项目的 redux数据流

image.png

index.ts

  1. import { MyModuleActions, MyModuleState } from './types';
  2. import { MY_MODULE_ACTIONS } from './action-types';
  3. export const initialState: MyModuleState = {
  4. data: null,
  5. };
  6. export default function MyModuleReducer(state = initialState, action: MyModuleActions): MyModuleState {
  7. switch (action.type) {
  8. case MY_MODULE_ACTIONS.SET_DATA:
  9. return {
  10. ...state,
  11. };
  12. default:
  13. return state;
  14. }
  15. }

action-type.ts

  1. export enum MY_MODULE_ACTIONS {
  2. SET_DATA = 'myModule/SET_DATA',
  3. }

action.ts

  1. import { Dispatch } from 'redux';
  2. import { MY_MODULE_ACTIONS } from './action-types';
  3. import { FetchDataAction } from './types';
  4. export const fetchData = (data: any) => (dispatch: Dispatch<FetchDataAction>) => {
  5. dispatch({ type: MY_MODULE_ACTIONS.SET_DATA, data });
  6. };

types.ts

类型约束

  1. import { Action } from 'redux';
  2. import { MY_MODULE_ACTIONS } from './action-types';
  3. export interface MyModuleState {
  4. data: any;
  5. }
  6. export type FetchDataAction = Action< MY_MODULE_ACTIONS.SET_DATA> & {
  7. }
  8. export type MyModuleActions = FetchDataAction;

component组件

  1. import React from 'react';
  2. type Props = {}
  3. export default function myComponent({}: Props) {
  4. return (<div className="my-component"/>);
  5. }