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

标签 reactjs redux react-redux connect

在我的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);

Loading组件的头部是:

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

如果我这样做,我就可以将 LoadingState 接口(interface)的属性用作 props。但是,如果我还想将 StatusState 中的属性用作同一组件中的 props,我该怎么办?

最佳答案

首先你的 props 还需要期望 StatusState

type LoadingProps = LoadingState & StatusState & typeof actionCreators

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

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

关于reactjs - 将多个 redux 子状态连接到 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47654541/

相关文章:

javascript - React.js 上的 JSX 相邻

node.js - 放大初始化错误 - ✖ 根堆栈创建失败初始化失败 TypeError : Cannot redefine property: default

javascript - 如何在通过 NPM 分发时管理 React 组件(Redux、CSS)的自定义方面

reactjs - React-router-dom 链接不起作用

javascript - 下面的语句在js中起什么作用

javascript - 了解 Redux 的基本实现 | prevState 是如何使用的?

html - React中的图片标签

reactjs - 如何测试componentDidUpdate()?

reactjs - 在 React Redux 存储中存储文件对象的最佳方式(从 DropZone 上传文件?)

reactjs - Ant 设计: get Id from datepicker in onChange