【问题标题】:Connect multiple redux sub-states to a React component将多个 redux 子状态连接到一个 React 组件
【发布时间】:2017-12-05 21:46:41
【问题描述】:

在我的 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
}

通常我在组件Loading中使用connect方法如下:

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

Loading 组件的头部为:

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

如果我这样做,我有 LoadingState 接口的属性可用作道具。但是,如果我还希望 StatusState 中的属性也可用作同一组件中的道具,我该怎么办?

【问题讨论】:

标签: reactjs redux react-redux connect


【解决方案1】:

首先你的 props 还需要期待 StatusState

type LoadingProps = LoadingState &amp; StatusState &amp; typeof actionCreators

那么你的 mapStateToProps 函数只需要返回一个包含所有映射属性的对象,最简单的方法是使用状态值中的扩展 (...)

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

【讨论】:

    猜你喜欢
    • 2020-05-05
    • 2018-07-17
    • 2020-10-20
    • 2018-09-12
    • 2021-09-08
    • 2013-06-28
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    相关资源
    最近更新 更多