【React】类型 Location<unknown> 上不存在属性 query - ts(2339)

本文详细介绍了在TypeScript和eslint环境下,如何处理React Router中获取URL参数时遇到的query属性缺失问题。通过扩展`Location`类型来添加`query`属性,并提供了具体的代码示例和解决方案,确保在工程中正确使用`RouteComponentProps`。同时,还给出了相关的学习资源链接以供进一步研究。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
  • 如果要在 TSeslint 的工程里使用 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值