我刚刚开始使用Typescript进行React/Redux项目,我不确定类型定义应该如何应用于应用程序状态。我正在试图通过mapStateToProps
向容器组件提供一段状态。但是我得到一个错误,说'状态'必须有一个类型定义。Redux商店状态的类型定义
function mapStateToProps (state) {
return {
deals: state.deals
};
}
我刚刚开始使用Typescript进行React/Redux项目,我不确定类型定义应该如何应用于应用程序状态。我正在试图通过mapStateToProps
向容器组件提供一段状态。但是我得到一个错误,说'状态'必须有一个类型定义。Redux商店状态的类型定义
function mapStateToProps (state) {
return {
deals: state.deals
};
}
您需要声明状态的类型和返回值类型。以下应该做的工作。
function mapStateToProps (state: any): any {
return {
deals: state.deals
};
}
如果你有类型定义或混凝土类,可以更换any
他们。
某些默认类型,您可以使用:
any
string
number
你需要创建一个代表整个应用程序状态的接口:
interface ApplicationState {
someProp1: {
someProp1a: string;
someProp1b: number;
};
someProp2: {
someProp1a: string;
someProp1b: number;
};
}
然后创建一个接口,它代表了每个智能组件的状态(通过mapStateToProps
连接到商店的组件):
interface SomeComponentState {
someProp1: {
someProp1a: string;
someProp1b: number;
};
}
MyComponentState
接口应该是AppState
的子集。这意味着你实际上可以做:
type SomeComponentProps = Pick<ApplicationState, "someProp1">;
您还需要声明一个类型为智能型组件的动作:
const actionsCreators = {
doSomething: (txt: string) => ({ type: "DO_SOMETHING", pleyload: txt })
};
type SomeComponentActions = { actions: typeof actionsCreators };
智能组件的属性是类型的工会其属性及其操作:SomeComponentProps & SomeComponentActions
。
class MyComponent extends React.Component<SomeComponentProps & SomeComponentActions, void> {
public render() {
return <div onClick={() => this.props.actions.doSomething(this.props.someProp1.someProp1a)} >Click me!</div>;
}
}
您从应用状态映射到组件状态:
function mapStateToProps(state: ApplicationState): SomeComponentProps {
return {
someProp1: state.someProp1
};
}
function mapDispatchToProps(dispatch: Redux.Dispatch<typeof actionsCreators>) {
return { actions : bindActionCreators(actionsCreators, dispatch) };
}
const MySmarthComponent = connect(mapStateToProps, mapDispatchToProps)(MyComponent);
非常感谢你打破下来这么多。但是,当我尝试将'mapStateToProps'的返回类型设置为'someComponentProps'时,我仍然遇到错误。它只有当我把它设置为“任何”时才有效。但请注意,我还没有任何操作设置 – Lexcorp16