javascript - React 和 typescript ReactRouterProps 问题
问题描述
我需要解构我的通用道具并匹配(从 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
但是当我传递道具时父组件显示错误
家长
<div>
<h1>Start Project Page</h1>
<AddResources
initialProjectName={initialProjectName}
workspaceId={workspaceId} // error
/>
</div>
错误信息
解决方案
通过使用RouteComponentProps
,您可以指定您的组件需要路由道具,但您还需要确保传递这些道具。如果组件直接位于 a 下方Route
(即作为子组件或通过 using <Route component={..}/>
,则路由 props 会自动传递,如果不是,您可以使用withRouter
( docs ) 获取它们:
const AddResourcesWithRouter = withRouter(AddResources);
并使用AddResourcesWithRouter
is而不是AddResources
.
推荐阅读
- c++ - 下面的注释与 [basic.start.main]/2 中的 (2.1) 和 (2.2) 段是否矛盾?
- python - 如何在xml中添加多个标签?
- sql - SQL Server - 创建返回扁平值的内部 JSON 查询
- javascript - 在 IE 上使用 Selection.getRangeAt 时出现“IndexSizeError”
- visual-c++ - 注册设备通知
- python - python中使用gpu加速库的n维滑动窗口操作,最好是Tensorflow?
- python-3.x - seaborn 2d kde图中的自定义最大和最小比例
- reactjs - 对 react-navigation 的引用在导入时会引发错误。我需要 webpack 吗?
- assembly - 汇编中的`js`和`jb`指令
- reactjs - 在反应中渲染来自 API 调用的 JSON 数据