[英]Type definition for Redux store state
I just got into using Typescript for a React/Redux project and I am unsure of how type definitions should be applied to application state. 我刚开始将Typescript用于React / Redux项目,但不确定如何将类型定义应用于应用程序状态。 I am trying to make a piece of state available to a container component through mapStateToProps
. 我正在尝试通过mapStateToProps
使状态可用于容器组件。 But I get an error saying 'state' must have a type definition. 但是我收到一个错误消息,说“状态”必须具有类型定义。
function mapStateToProps (state) { return { deals: state.deals }; }
You need to create an interface that represents the entire application state: 您需要创建一个代表整个应用程序状态的接口:
interface ApplicationState {
someProp1: {
someProp1a: string;
someProp1b: number;
};
someProp2: {
someProp1a: string;
someProp1b: number;
};
}
Then create one interface that represents the state for each smart component (a component that is connected to the store via mapStateToProps
): 然后创建一个代表每个智能组件(通过mapStateToProps
连接到商店的mapStateToProps
)状态的接口:
interface SomeComponentState {
someProp1: {
someProp1a: string;
someProp1b: number;
};
}
The MyComponentState
interface should be a subset of AppState
. MyComponentState
接口应该是AppState
的子集。 This means that you can actually do: 这意味着您实际上可以执行以下操作:
type SomeComponentProps = Pick<ApplicationState, "someProp1">;
You also need to declare a type for the actions of the smart component: 您还需要为智能组件的操作声明一种类型:
const actionsCreators = {
doSomething: (txt: string) => ({ type: "DO_SOMETHING", pleyload: txt })
};
type SomeComponentActions = { actions: typeof actionsCreators };
The properties of the smart component is the union of the type of its properties and its actions: SomeComponentProps & SomeComponentActions
. 智能组件的属性是其属性类型及其操作的并集: 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>;
}
}
You are mapping from the application state to the component state: 您正在从应用程序状态映射到组件状态:
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);
You need to declare the type of state and the return type. 您需要声明状态的类型和返回类型。 Following should do the job. 以下应该做的工作。
function mapStateToProps (state: any): any {
return {
deals: state.deals
};
}
If you got type definitions or concrete classes, you can replace the any
with them. 如果您有类型定义或具体类,则可以用它们替换any
。
Some default types you can use: 您可以使用一些默认类型:
any
string
number
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.