gpt4 book ai didi

reactjs - 如何在 React Typescript 中绑定(bind)匹配项?

转载 作者:行者123 更新时间:2023-12-05 07:39:37 25 4
gpt4 key购买 nike

我有这个代码:

...
import { match, RouteComponentProps } from "react-router";
import * as H from 'history';

interface oneRoute {
path: string;
exact?: boolean;
main: any;
}

interface ITestProps {
id: string;
}

class Test extends React.Component<RouteComponentProps<ITestProps>, {}> {
public render() {
return <div>Hallow id:{this.props.match.params.id} -- {JSON.stringify(this.props.match)}</div>
}
}

export const routesData: oneRoute[] = [
{
path: '/',
exact: true,
main: (match: match<any>, location: H.Location, history: H.History) => <Home match={match} location={location} history={history} />
},

{
path: '/test/:id',
exact: false,
main: (match: match<ITestProps>, location: H.Location, history: H.History) => <Test match={match} location={location} history={history} />
}
]

export const routes = <Layout>
{
routesData.map((route, index) => {
return <Route exact={route.exact} key={index} path={route.path} component={route.main} />;
})
}
</Layout>;

我在链接“/test/12”上的测试中出现错误。

Uncaught TypeError: Cannot read property 'id' of undefined.

如果我评论 this.props.match.params.idJSON.stringify(this.props.match) 显示 "match":{"path":"/test/:id","url":"/test/12","isExact":true,"params":{"id":"12"}} 所以有 参数.id。怎么会这样,如何解决获取this.props.match.params.id的问题?

最佳答案

你在这里设置它的方式,你的组件 Test得到一个名为 match 的参数具有名为 match属性上面有你想要的实际对象 ( this.props.match.match.params.id )。

你告诉了你的Routecomponent渲染是:

(match: match<ITestProps>, location: H.Location, history: H.History) => <Test match={match} location={location} history={history} />

组件只能用一个参数调用,它是一个 props 对象。在运行时,变量 match这里不是match<ITestProps> , 这是整个 RouteComponentProps对象。

Typescript 在设置 component={route.main} 时不会警告您因为route.main类型是 any ,因此假定它是兼容的。

在你的界面中更具体:

interface oneRoute {
path: string;
exact?: boolean;
main: React.ComponentType<RouteComponentProps<any>>;
}

你可以有 main是破坏属性的函数match , location , 和 history并将它们传递给组件,但鉴于您没有更改任何 Prop ,这真的没有意义。 main可以只是组件本身。

export const routesData: oneRoute[] = [
{
path: '/',
exact: true,
main: Home,
},
{
path: '/test/:id',
exact: false,
main: Test,
}
]

关于reactjs - 如何在 React Typescript 中绑定(bind)匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47002911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com