TypeScript配合react-router-dom用history.push跳转报TS2769错如何解决?
问题根因
你出现这个报错是因为混淆了 react-router v5 中 <Link> 组件的属性和 history.push 方法的入参规范:to 是 <Link> 组件指定跳转路径的属性,history.push 接收的对象参数中,路径对应的key是 pathname,不是 to。
修正步骤
- 修正跳转代码
把跳转参数里的to改成pathname即可解决报错:
const handleVideoSelect = (): void => { history.push({ pathname: `/video/${video.id.videoId}`, state: {video, opts} }); };
你也可以用更简洁的传参写法,直接把路径当第一个参数、state当第二个参数:
history.push(`/video/${video.id.videoId}`, {video, opts})
- 移除不必要的高阶组件包裹
函数组件中已经用了useHistory钩子获取history对象,不需要再用withRouter高阶组件包裹导出,直接导出原组件即可:
// 原写法 export default withRouter(VideoCard); 替换为下面的代码 export default VideoCard;
- 目标组件正确接收传递参数
你当前的目标组件没有接收入口props,调整后才能拿到跳转携带的state数据,有两种实现方式可选:
- 方式1:保留withRouter,通过props取参数
import React from 'react'; import { Options } from 'react-youtube'; import { VideoDataType } from '../Shared/VideoDataType/VideoDataType'; import { RouteComponentProps, withRouter } from 'react-router-dom'; // 定义跳转传递的state类型,避免类型警告 interface PageState { video: VideoDataType; opts: Options; } interface ChildComponentProps extends RouteComponentProps<{}, any, PageState> {} const SingleVideoDisplayerPage = (props: ChildComponentProps): React.ReactElement => { // 从props中拿到传递的参数 const { video, opts } = props.location.state; return ( <div> <h6> jksdgfdsghjfkd </h6> </div> ); }; export default withRouter(SingleVideoDisplayerPage);
- 方式2:用useLocation钩子,不需要withRouter包裹
import React from 'react'; import { Options } from 'react-youtube'; import { VideoDataType } from '../Shared/VideoDataType/VideoDataType'; import { useLocation } from 'react-router-dom'; const SingleVideoDisplayerPage = (): React.ReactElement => { const location = useLocation<{video: VideoDataType, opts: Options}>(); const { video, opts } = location.state; return ( <div> <h6> jksdgfdsghjfkd </h6> </div> ); }; export default SingleVideoDisplayerPage;
内容的提问来源于stack exchange,提问作者kyrolos magdy
相关产品推荐
相关产品推荐

