反应和打字稿 ReactRouterProps 问题

时间:2021-04-22 15:13:51

标签: javascript node.js reactjs typescript react-router

我需要解构我的通用道具并匹配(从 URL 中获取 "id")。

<块引用>

组件(使用道具):

interface Props  extends RouteComponentProps<{id: string}>{
  initialProjectName: string;
  workspaceId: string;
}

const AddResources: React.FC<Props> = ({
  initialProjectName,
  workspaceId,
  match,
}) => {
  const projectId = match.params.id; // used here without any error

但是当我传递 props 时父组件显示错误

<块引用>

家长

<div>
      <h1>Start Project Page</h1>
      <AddResources
        initialProjectName={initialProjectName}
        workspaceId={workspaceId}   // error
      />
    </div>

错误信息

enter image description here

2 个答案:

答案 0 :(得分:1)

通过使用 RouteComponentProps,您可以指定您的组件需要路由道具,但您还需要确保传递这些道具。如果组件直接位于 Route 之下(即作为子组件或使用 <Route component={..}/>,路由道具会自动传递,否则,您可以使用 withRouter (docs ) 来获取它们:

const AddResourcesWithRouter = withRouter(AddResources);

并使用 AddResourcesWithRouter 代替 AddResources

答案 1 :(得分:0)

我认为你应该尝试 useHistory、useRouteMatch、useLocation 或 wrap withRouter(AddResources)