簡體   English   中英

如何在 React / Redux mergeProps 中使用 TypeScript

[英]How to use TypeScript with React / Redux mergeProps

我有以下幾點:

'use strict';

import {AppDispatch} from '../cp';
import {RootState} from '../reducers/root';
import {OwnProps} from '../components/example/better-example';

export function mapDispatch(dispatch: AppDispatch<any>) {
  return {dispatch};
}

export function mapState(state: RootState) {
  return {state};
}

export const mergeProps = <OwnProps>(
  propsFromState: StateProps,
  propsFromDispatch: DispatchProps,
  propsFromParent: OwnProps
) => {
  return {
    dispatch: propsFromDispatch.dispatch,
    s: propsFromState.state,
    o: propsFromParent
  };
};

export type MergeProps<OwnProps> = ReturnType<typeof mergeProps>;
export type StateProps = ReturnType<typeof mapState>;
export type DispatchProps = ReturnType<typeof mapDispatch>;

問題是我不知道如何將<OwnProps>類型向下傳播到傳遞給connect()mergeProps函數的ReturnType ,如下所示:

export default connect<StateProps, DispatchProps, OwnProps, MergeProps<OwnProps>>(
  mapState as any,
  mapDispatch,
  mergeProps   /// passed here
)(MyComponent);

我不得不添加一個論點:

export type MergedProps<T> = {
  dispatch: DispatchProps["dispatch"],
  s: StateProps["state"],
  o: T
};

export default connect<StateProps, DispatchProps, OwnProps, MergeProps<OwnProps>, RootState>(
  mapState,
  mapDispatch,
  mergeProps  
)(MyComponent);

必須將 RootState 作為第 5 個參數傳遞。

https://redux.js.org/recipes/usage-with-typescript/#typing-the-connect-higher-order-component

    const connector = connect(mapState, mapDispatch,mergeProps)(connectedComponent)
    type PropsFromRedux = ConnectedProps<typeof connector>

    const connectedComponent =(props:PropsFromRedux)=> {
      return //
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM