reactjs - 在 react typescript 组件上实现 RouteComponentProps 时使用什么类型
问题描述
我正在尝试使用 react-router-dom 制作我的第一个接收参数的组件。这是我的组件:
const ProductDetailsPage: React.FC<IPage & RouteComponentProps<any>> = (props: Props) => {
useEffect(() => {
const id = props.match.params.id;
}
return <h1>product details</h1>
}
interface Props {
match: {
params: {
id: string | undefined;
};
};
}
这里 eslint 向我显示了一个我不应该使用的警告,any
但我不明白在这里设置什么类型。
我也写了props: Props
,但我不知道这是否是这样做的正确方法。
更新更多预览代码:
export default interface IPage {
name: string;
}
const routes: IRoute[] = [
{
path: '/products/:id',
name: 'details',
component: ProductDetailsPage,
exact: true,
},
];
const ProductsPage: React.FC<IPage> = () => {
const match = useRouteMatch();
return (
<div>
<h4>This is products page</h4>
<div>
<Link to={`${match.url}/44`}>Product 44</Link>
<Link to={`${match.url}/45`}>Product 44</Link>
<Link to={`${match.url}/46`}>Product 44</Link>
</div>
<Switch>
{routes.map((route, index) => {
return (
<Route
key={index}
path={route.path}
render={(props: RouteComponentProps<any>) => (
<route.component name={route.name} {...props} {...route.props} />
)}
/>
);
})}
</Switch>
</div>
);
};
interface Props {
match: {
params: {
id: string | undefined;
};
};
}
const ProductDetailsPage: React.FC<IPage & RouteComponentProps<Props>> = (props) => {
const [message, setMessage] = useState<string>('');
useEffect(() => {
const id = props.match.params.id;
if (id) {
setMessage(`Show details for product: ${id}`);
} else {
setMessage(`No parameter passed`);
}
}, [props.match.params.id]);
return <h4>{message}</h4>;
};
export default withRouter(ProductDetailsPage);
解决方案
中的泛型 ( T
)RouteComponentProps<T>
定义了 params 类型。
参数值始终是 astring
或undefined
。
如果参数未知,最好使用Record<string, string | undefined>
输入参数。
type Params = { id: string | undefined; };
const Test: React.FC<RouteComponentProps<Params>> = ({
match: { params: { id } }
}) => {
const idIsStringOrUndefined: string | undefined = id;
return null;
}
道具也应该通过使用React.FC<RouteComponentProps<Params>>
.
推荐阅读
- python - 如果我的项目依赖于 scipy 的一个功能,我的项目是否必须包含整个 scipy 包?
- scala - 如何在 Scala 的列表中查找重复项?
- c# - C# 在不按住按钮的情况下单击按钮时运行耗时的方法
- actions-on-google - 如何打断谷歌助理讲话?
- java - 在独立 JAR 应用程序中集成 DB2 许可证
- c++ - 如何在 QT 中实现垂直制表符?
- node.js - 我想使用 Node js 在 Pagerduty 中创建一个用户。但我做不到。有人可以帮助我吗?
- android - Android上的MongoDB - 套接字超时
- .htaccess - 重定向到本地主机仪表板而不是项目根目录
- node.js - elasticsearch:错误:无法解析/序列化正文