我试图切换旧项目以使用react和react-router。我也是用于项目的打字稿的新手,所以任何解释都将不胜感激。
该路线的定义如下:
<Route
path="/deployments/:somePrefix/:someId"
component={SomeDetailPage}/>
但是,在SomeDetailPage中,当我尝试访问参数以便我可以调用它们上的函数((this.props.match.params.somePrefix
或this.proper.match.params.someId)
)时,我收到此错误:
ERROR in [at-loader] src/public/components/some-detail-page.tsx:25:97
Property 'somePrefix' does not exist on type '{}'
ERROR in [at-loader] src/public/components/some-detail-page.tsx:25:97
Property 'someId' does not exist on type '{}'
然而,我知道那些参数存在,因为当我尝试测试并将参数作为div的一部分(只是随机测试)时,div不会加载并且我收到此错误:
Objects are not valid as a React child (found: object with keys {somePrefix, someId})
答案 0 :(得分:2)
您如何为SomeDetailPage
键入道具?
您需要确保从RouteComponentProps
正确添加react-router-dom
。
例如,你需要的东西是
import * as React from 'react';
import { RouteComponentProps } from 'react-router-dom';
// Define what your match should look like
interface SomeDetailPageMatch {
somePrefix: string;
someId: string;
}
interface SomeDetailPagePropsFromParent {
// Your custom props here
}
type SomeDetailPageProps = SomeDetailPagePropsFromParent &
RouteComponentProps<SomeDetailPageMatch>; // Provide your match as generic
class SomeDetailPage extends React.Component<SomeDetailPageProps> {
...
然后它应该理解this.props.match.params.someId
和this.props.match.params.somePrefix
存在。