如何为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
相关产品推荐
相关产品推荐

