2017-09-03 118 views
0

我現在有打字稿問題,在react路由器中傳遞正確的類型。如何將容器組件傳遞到react-router-dom路由?

打字稿錯誤:

severity: 'Error' 
message: 'Type '{ path: "/foo/:id"; component: typeof "<path>..' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Route> & Readonly<{ children?: ReactNode; }> & Rea...'. 
     Type '{ path: "/foo/:id"; component: typeof "<path>..' is not assignable to type 'Readonly<RouteProps>'. 
     Types of property 'component' are incompatible. 
      Type 'typeof "<path>..' is not assignable to type 'StatelessComponent<RouteComponentProps<any>> | ComponentClass<RouteComponentProps<any>>'. 
      Type 'typeof "<path>..' is not assignable to type 'ComponentClass<RouteComponentProps<any>>'. 
       Type 'typeof "<path>..' provides no match for the signature 'new (props?: RouteComponentProps<any>, context?: any): Component<RouteComponentProps<any>, ComponentState>'.' 

這似乎發生,因爲我傳遞一個容器組件到<Route... />。然而,我不清楚爲什麼這不起作用,因爲mapsToProps應該返回一個RouteComponentProps。

Foo.ts(成分):

export interface Props extends RouteComponentProps<any> { 
    a: string; 
} 

export class Foo extends React.Component<Props, void> { 
    public render() { 
     //code 
    } 
} 

FooContainer.ts:

function mapStateToProps(state: State, ownProps: Props): Props { 
    const mappedProps: Props = { 
     foo: "super" 
    }; 

    return mappedProps; 
} 

export default connect(mapStateToProps)(Foo); 

路線:

import * as React from "react"; 
import { Route, Switch } from "react-router-dom"; 
import FooContainer from "./FooContainer"; 
export const routes = (
    <Switch> 
     <Route path="/foo/:id" component={FooContainer} /> 
    </Switch> 
); 

NOM庫/版本:

"@types/react": "^16.0.5", 
"@types/react-dom": "^15.5.4", 
"@types/react-redux": "4.4.40", 
"@types/react-router-dom": "4.0.7", 
"@types/react-router-redux": "5.0.8", 
"react": "^15.6.1", 
"react-dom": "^15.6.1", 
"react-redux": "5.0.4", 
"react-router-dom": "4.2.2", 
"react-router-redux": "5.0.0-alpha.6", 

如果你看一下我的道具,它擴展RouteComponentProps是:

export interface RouteComponentProps<P> { 
    match: match<P>; 
    location: H.Location; 
    history: H.History; 
} 

如果這是真的,不應該mapStateToProps包含匹配?

回答

0

所以我解決此問題得到了與:

export default connect(mapStateToProps)(foo) as React.ComponentClass<any>; 

不知道爲什麼我需要指定與React.ComponentClass返回類型。它不是隱含的嗎?

相關問題