2017-06-13 111 views
0

我剛剛開始使用Typescript進行React/Redux項目,我不確定類型定義應該如何應用於應用程序狀態。我正在試圖通過mapStateToProps向容器組件提供一段狀態。但是我得到一個錯誤,說'狀態'必須有一個類型定義。Redux商店狀態的類型定義

function mapStateToProps (state) { 
 
    return { 
 
    deals: state.deals 
 
    }; 
 
}

回答

-1

您需要聲明狀態的類型和返回值類型。以下應該做的工作。

function mapStateToProps (state: any): any { 
    return { 
    deals: state.deals 
    }; 
} 

如果你有類型定義或混凝土類,可以更換any他們。

某些默認類型,您可以使用:

any 
string 
number 
0

你需要創建一個代表整個應用程序狀態的接口:

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); 
+0

非常感謝你打破下來這麼多。但是,當我嘗試將'mapStateToProps'的返回類型設置爲'someComponentProps'時,我仍然遇到錯誤。它只有當我把它設置爲「任何」時纔有效。但請注意,我還沒有任何操作設置 – Lexcorp16