dav*_*vez 3 connect reactjs redux react-redux
在我的 react-redux-typescript 应用程序中,我有多个子状态构成应用程序状态。申请状态如下。
interface AppState {
dialogs: DialogState,
messages: MessageState,
notifications: NotificationsState,
errors: ErrorState
loading: LoadingState,
status: StatusState;
}
Run Code Online (Sandbox Code Playgroud)
我使用connect方法将 React 组件中可用的子状态之一作为props. 但是现在我有一个案例,我需要一个组件中的两个子状态属性作为它的props.
具体这些部分:
interface LoadingState {
size: number
available: boolean
}
interface StatusState {
name: string
}
Run Code Online (Sandbox Code Playgroud)
通常,我在组件Loading中使用connect方法如下:
export default connect(
(state: AppState) => state.loading, actionCreators)(Loading);
Run Code Online (Sandbox Code Playgroud)
Loading 组件的头部是:
type LoadingProps = LoadingState & typeof actionCreators;
class Loading extends React.Component<LoadingProps, {}>
Run Code Online (Sandbox Code Playgroud)
如果我这样做,我就有了LoadingState可用作道具的界面属性。但是,如果我还想要StatusState在同一组件中作为 props 使用的属性,我该怎么办?
首先你的道具还需要期待 StatusState
type LoadingProps = LoadingState & StatusState & typeof actionCreators
然后你的 mapStateToProps 函数只需要返回一个包含所有映射属性的对象,最简单的方法是使用状态值的传播 (...)
export default connect(
(state: AppState) => ({...state.loading, ...state.status }),
actionCreators
)(Loading)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1081 次 |
| 最近记录: |