将多个 redux 子状态连接到 React 组件

Connect multiple redux sub-states to a React component

在我的 react-redux-typescript 应用程序中,我有多个子状态构成应用程序状态。申请状态如下

interface AppState {
    dialogs: DialogState,
    messages: MessageState,
    notifications: NotificationsState,
    errors: ErrorState
    loading: LoadingState,
    status: StatusState;
}

我使用 connect 方法获取 React 组件中可用的子状态之一,如 props。但是现在我有一个情况,我需要一个组件中的两个子状态属性作为它的 props.
具体是这些部分:

interface LoadingState {
    size: number
    available: boolean
}

interface StatusState {
    name: string
}

平时我在组件加载中使用connect方法是这样的:

export default connect(
(state: AppState) => state.loading, actionCreators)(Loading);

加载组件的头部是:

type LoadingProps = LoadingState & typeof actionCreators;
class Loading extends React.Component<LoadingProps, {}>

如果我这样做,我就有了 LoadingState 接口的属性作为道具。但是,如果我还想将 StatusState 中的属性用作同一组件中的道具,我该怎么办?

首先你的道具也需要 StatusState

type LoadingProps = LoadingState & StatusState & typeof actionCreators

那么你的 mapStateToProps 函数只需要 return 一个包含所有映射属性的对象,最简单的方法是使用来自状态值的传播 (...)

export default connect(
  (state: AppState) => ({...state.loading, ...state.status }),
  actionCreators
)(Loading)