2017-06-04 16 views
0

我最近從TypeScript 2.1升級到新版本,並開始使用我的示例中的所有模仿我的React組件的錯誤。在升級之前,這種嵌套組件模式並未用於造成任何問題。升級到更新版本的TypeScript後嵌套組件的問題

組件#1:

interface ISpinnerProps{ 
    showGlobalSpinner: boolean; 
} 

class SpinnerClass extends React.Component<ISpinnerProps, undefined> { 
    render() { 
     return (
     // Some markup 
     ) 
    } 
} 

export const Spinner = connect((state: State) => { 
    return { 
    showGlobalSpinner: selectors.showGlobalSpinner(state), 
    } 
})(SpinnerClass) 

部分#2:

interface IProps { 
    loginStatus: fb.LoginStatus 
} 


class AppClass extends React.Component<IProps, undefined> { 
    render() { 
     return (
     // Some markup 
     <Spinner/> // Error is thrown here. 
     ) 
    } 
} 
export const App = connect(mapStateToProps, actionCreators)(AppClass) 

這將導致錯誤: Type '{}' is not assignable to type 'Readonly<ISpinnerProps>'. Property 'showGlobalSpinner' is missing in type '{}

編譯器要我設置的屬性父母的孩子,但這些屬性由Redux處理。有沒有人遇到類似的問題?

+0

只要選中道具作爲可選的'''showGlobalSpinner:booelan;'我認爲會做 – WilomGfx

回答

3

你需要做的是將你的道具分成從redux(IMappedProps和IMappedActions)映射的道具和動作,以及你希望從父組件(IOwnProps)傳遞到你的組件的道具。

然後在你的連接功能,你可以指定哪些道具是哪個。

export default connect<IMappedProps, IMappedActions, IOwnProps>(mapStateToProps, mapDistpatchToProps)(SpinnerClass); 

在你的情況,微調組件只有一個從redux映射的道具。你的連接功能看起來是這樣的:

export default connect<ISpinnerProps, null, null>(mapStateToProps, null)(SpinnerClass); 

注爲清晰起見,我建議重命名ISpnnerProps到IMappedProps。

爲了進一步參考看看反應,終極版打字稿定義 - https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-redux/index.d.ts

+0

這是一個偉大的答案尼克?。正如我所提到的,我在使用這種模式的許多組件中遇到了這個問題。這種方法解決了連接了一些狀態和動作的組件的問題。但是對於像Spinner這樣的組件,我無法聲明爲Actions: '(mapStateToProps,null)'我得到這個錯誤: message:'類型'null'的參數不能分配給參數類型'MapDispatchToPropsParam cinnaroll45

+1

@ cinnaroll45,不用擔心,樂意幫忙。你能否檢查你是否擁有最新版本的@ types/react-redux和react-redux? – Nick

+0

目前該項目有:'@ types/react-redux:4.4.41'和'react-redux:5.0.5'。該組件在這裏: https://pastebin.com/wCZTqhfz – cinnaroll45