【问题标题】:How to pass container components into react-router-dom Route?如何将容器组件传递到 react-router-dom 路由中?
【发布时间】:2018-02-12 02:45:51
【问题描述】:

我目前在 react router redux 中传递正确类型时遇到打字稿问题。

打字错误:

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>'.'

这似乎正在发生,因为我正在将一个容器组件传递给&lt;Route... /&gt;。但是,我不清楚为什么这不起作用,因为 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>
);

标称库/版本:

 "@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",

如果您查看我的 Props,它会扩展 RouteComponentProps,即:

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

如果是这样,mapStateToProps 不应该包含匹配项吗?

【问题讨论】:

    标签: react-router-v4 react-router-redux react-router-dom


    【解决方案1】:

    所以我解决了这个问题:

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

    不知道为什么我需要用 React.ComponentClass 指定返回类型。不是隐含的吗?

    【讨论】:

      猜你喜欢
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-14
      • 2018-06-04
      • 2019-01-28
      • 1970-01-01
      • 2020-04-02
      • 2021-02-07
      相关资源
      最近更新 更多