点击react-router-dom的Link时获取路径报错:this.match未定义
解决React Router中
this.match is undefined及路由跳转控制问题 你遇到的this.match is undefined错误,本质是因为你的NavTransitions组件没拿到React Router提供的路由相关props——match是由<Route>组件传递给它渲染的子组件的,要是你的组件没被<Route>直接渲染,也没做其他处理,自然拿不到这个属性。
另外,你想要点击<Link>时阻止默认路由动画、自定义路径后再修改history的需求,我给你两种可行的解决方案:
方案一:用withRouter高阶组件注入路由props
withRouter是React Router提供的工具,能把history、match、location这些路由相关props注入到任意组件里,不管它是不是被<Route>直接渲染。
修改后的代码如下:
import React from 'react'; import { Link, withRouter } from "react-router-dom"; class NavTransitions extends React.Component { constructor(props) { super(props); this.changeRoutePath = this.changeRoutePath.bind(this); } changeRoutePath(e) { // 先阻止默认的路由跳转行为,避免触发内置动画 e.preventDefault(); // 这里可以获取并修改你要跳转的路径,比如原Link的to是"/item" const targetPath = "/item"; // 举个例子,给路径加个前缀,你可以根据自己的需求修改 const modifiedPath = `/custom${targetPath}`; // 手动调用history.push完成跳转 this.props.history.push(modifiedPath); console.log('修改后的跳转路径:', modifiedPath); console.log('changeRoutePath 已触发'); } render() { return( <div> <Link to="/item" onClick={this.changeRoutePath}>Prevent</Link> </div> ); } } // 关键一步:用withRouter包裹组件,注入路由props export default withRouter(NavTransitions);
方案二:把组件放在<Route>中渲染
如果你更倾向于通过<Route>传递props,可以在路由配置或者父组件里这样写:
// 比如在你的App.js或者路由配置文件中 import { Route } from 'react-router-dom'; import NavTransitions from './NavTransitions'; function App() { return ( <div className="App"> {/* 用component属性直接渲染组件,Route会自动传递路由props */} <Route path="/" component={NavTransitions} /> {/* 或者用render属性,还能额外传递自定义props */} {/* <Route path="/" render={(routerProps) => <NavTransitions {...routerProps} customProp="value" />} /> */} </div> ); }
这样你的NavTransitions组件就能直接通过this.props.match访问到match对象了,同时也能正常使用this.props.history来控制跳转。
另外补充个小技巧:如果你的<Link>是动态生成的,不想硬编码路径,可以把目标路径作为参数传给点击事件,比如:
<Link to="/item" onClick={(e) => this.changeRoutePath(e, "/item")}>Prevent</Link>
然后在方法里接收并处理:
changeRoutePath(e, targetPath) { e.preventDefault(); const modifiedPath = `${targetPath}/detail`; // 自定义修改路径 this.props.history.push(modifiedPath); }
内容的提问来源于stack exchange,提问作者Leo1234562014
相关产品推荐
相关产品推荐

