author: jwensh
date: 2022.04.21
1. 获取 URL 参数,使用 RouteComponentProps 提示报错
import React, { useState } from 'react';
import { RouteComponentProps } from 'react-router-dom';
interface UrlParamType {
id: string;
}
type DetailProps = RouteComponentProps<UrlParamType>;
const Detail: React.FC<DetailProps> = (props: DetailProps) => {
const [urlParams, setUrlParams] = useState(props.location.query);
···
}
eslint
报错提示: 类型“Location<unknown>”上不存在属性“query”。ts(2339)
2. RouteComponentProps 使用方式
- 引入
RouteComponentProps
类型, 类组件和函数式组件
import { RouteComponentProps} from 'react-router-dom';
// 类
export interface DetailProps extends RouteComponentProps {
}
// 函数
interface UrlParamType {
id: string;
}
type DetailProps = RouteComponentProps<UrlParamType>;
RouteComponentProps
中的定义
import * as H from 'history';
export interface RouteComponentProps<
Params extends { [K in keyof Params]?: string } = {},
C extends StaticContext = StaticContext,
S = H.LocationState
> {
history: H.History<S>;
location: H.Location<S>;
match: match<Params>;
staticContext?: C | undefined;
}
H.Location<S>
中的定义没有query
export interface Location<S = LocationState> {
pathname: Pathname;
search: Search;
state: S;
hash: Hash;
key?: LocationKey | undefined;
}
- 如果要在
TS
和eslint
的工程里使用 query, 需要扩展下Location
类型
3. 扩展 Location 类型, 添加 query 属性类型
import { RouteComponentProps} from 'react-router-dom';
import H from 'history';
interface Location extends H.Location{
query: {[key: string]: string};
}
export interface DetailProps extends RouteComponentProps {
location: Location;
}
如果要指定具体的 URL 参数可以使用
import { RouteComponentProps} from 'react-router-dom';
import H from 'history';
// 指定 url 参数名
interface UrlParamType {
id: string;
}
interface Location extends H.Location{
query: UrlParamType;
}
export interface DetailProps extends RouteComponentProps {
location: Location;
}
const Detail: React.FC<DetailProps> = (props: DetailProps) => {
const [urlParams, setUrlParams] = useState(props.location.query);
···
}
4. 拓展学习
https://reactrouter.com/docs/en/v6/examples/custom-query-parsing
https://stackblitz.com/github/remix-run/react-router/tree/main/examples/search-params?file=src/App.tsx
https://stackblitz.com/github/remix-run/react-router/tree/main/examples/custom-query-parsing?file=src/App.tsx
https://github.com/remix-run/react-router/blob/main/docs/getting-started/tutorial.md