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