带有redux的打字稿,如何使用连接而无需重新执行操作定义



我对打字稿和redux-thunk动作有一些不便。

基本上,我的组件大量利用了react-redux连接到绑定动作创建者,问题是,当我在组件中创建此redux操作的接口时,我必须重新删除函数定义,因为它会丢失连接呼叫。

这是一个示例代码:

动作创造者

import api from './api';
import { Dispatch } from 'redux';
import { IReduxAction } from 'model';
export const FETCH_ENTITY = 'location/FETCH_ENTITY';
export function fetchEntity(id: string) {
  return (dispatch: Dispatch<IReduxAction>) => {
    dispatch({type: `${FETCH_ENTITY}_REQUEST`, payload: {id}});
    return api.fetchEntity(id)
              .then((res) => {
                dispatch({ type: `${FETCH_ENTITY}_DONE`, payload: res });
                return res;
              })
              .catch((err) => {
                dispatch({type: `${FETCH_ENTITY}_FAIL`, payload: err, error: true});
                throw err;
              });
  };
}

组件

import * as React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import {
  fetchEntity,
} from 'actions';
interface IStateProps {
  startingEntities: any[];
}
interface IDispatchProps {
  fetchEntity: (id: string) => Promise<any>; // <- this is what I'm trying to get rid of, basically whenever I change the action creator I have to change this definition everytime
}
class Dashboard extends React.Component<IStateProps & IDispatchProps, void> {
  public render() {
    return (<div>...RENDER SOMETHING...</div>);
  }
}
const mapStateToProps = (state: any, ownProps: any) => {
  const startingEntities = foo(); // not important
  return {
    startingEntities,
  };
};
const mapDispatchToProps = (dispatch: any) => {
  return bindActionCreators({
    fetchEntity
  }, dispatch);
};
export default connect<IStateProps, IDispatchProps, void>(mapStateToProps, mapDispatchToProps)(Dashboard);

无论如何是否有任何围栏的动作创建者不必每次在每个文件上重新销售它?

您无需再次定义功能类型。您可以使用typeof

interface IDispatchProps {
  fetchEntity: typeof fetchEntity
}

我对Typescript并不熟悉(大多数是为库接口完成的index.d.ts文件(,但是您应该能够通过正确键入fetchEntity来获取类型系统来为您完成工作并将其导出以供IDispatchProps使用。像

//...
import { ThunkAction } from 'redux-thunk'
//...
export interface FetchEntity {
  (id: string): ThunkAction<Promise<any>, IReduxAction, any>;
}
//...
export const fetchEntity: FetchEntity = (id: string) => {
  return (dispatch: Dispatch<IReduxAction>) => {
    //...
  };
}

然后您可以导入并使用相同的定义

//...
import {
  fetchEntity,
  FetchEntity
} from 'actions';
//...
interface IDispatchProps {
  fetchEntity: FetchEntity
}
//...

我不确定要理解您要寻找的设计模式,但是动作创建者只是一个简单的对象,当还原器使用时,属性"类型"。

因此,我认为处理的最佳方法是用您的操作获取专用文件,然后将其导出然后导入它们。您对DispATC选择的逻辑将是您的组件行为,这在我看来更好。

我希望这会有所帮助并解决您的问题:(

最新更新