Osc*_*nco 7 typescript reactjs redux react-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;
});
};
}
Run Code Online (Sandbox Code Playgroud)
零件
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);
Run Code Online (Sandbox Code Playgroud)
无论如何都要声明这个绑定的动作创建者,而不必每次在每个文件上重新声明它?
您无需再次定义函数类型.你可以使用typeof:
interface IDispatchProps {
fetchEntity: typeof fetchEntity
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2377 次 |
| 最近记录: |