You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为mapDispatchToProps中获取的location参数正确设置类型

解决方案

你标注不生效的核心原因是混用了类型:RouteProps 是路由组件的配置属性类型,不是组件接收到的路由属性集合类型,需要替换为对应版本的路由属性类型即可。

方案1:React Router v5 版本适配

首先导入对应类型:
import { RouteComponentProps } from 'react-router-dom';
给mapDispatchToProps的第二个参数(即组件自有props)标注类型,修改后代码如下:

const mapDispatchToProps = (dispatch: ThunkDispatch<any, any, any>, ownProps: RouteComponentProps) => {
    const { location } = ownProps;
    return {
        checkAuth: () => dispatch(checkAuth(location.pathname))
    }
}

如果你的组件还有其他自定义props,可以继承RouteComponentProps扩展类型:

interface OwnProps extends RouteComponentProps {
  // 在这里添加你的自定义属性类型
  id: number;
  title: string;
}

const mapDispatchToProps = (dispatch: ThunkDispatch<any, any, any>, { location }: OwnProps) => {
    return {
        checkAuth: () => dispatch(checkAuth(location.pathname))
    }
}

方案2:React Router v6 版本适配

v6版本移除了RouteComponentProps,直接导入Location类型标注即可:
首先导入类型:
import { Location } from 'react-router-dom';
修改后代码:

interface OwnProps {
  location: Location;
  // 其他自定义属性加在这里
}

const mapDispatchToProps = (dispatch: ThunkDispatch<any, any, any>, { location }: OwnProps) => {
    return {
        checkAuth: () => dispatch(checkAuth(location.pathname))
    }
}

更推荐的写法(函数式组件)

如果使用函数式组件,无需声明mapDispatchToProps,直接用React Redux和React Router提供的钩子即可,类型会自动推导:

import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';

const YourComponent = () => {
  const dispatch = useDispatch<ThunkDispatch<any, any, any>>();
  const location = useLocation();
  const checkAuth = () => dispatch(checkAuth(location.pathname));

  // 组件业务逻辑
}

内容的提问来源于stack exchange,提问作者DevOverflow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:39:03