一、问题场景:
在组件中想使用函数式路由跳转,根据官方文档查到:需要在该组件导出时 使用 withRouter(组件) 包裹组件;但是报错了!?
官方文档 https://reactrouter.com/web/api/matchPath
You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.
百度翻译:您可以通过withRouter高阶组件访问历史对象的属性和最近的匹配。withRouter将在呈现时向包装组件传递更新的match,location和history。
大概意思就是 使用 withRouter 包裹的组件,
会给该组件props中注入 match,location和history。
官方案例
import React from "react";
import PropTypes from "prop-types";
import { withRouter } from "react-router";
// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
static propTypes = {
match: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
history: PropTypes.object.isRequired
};
render() {
const { match, location, history } = this.props;
return <div>You are now at {location.pathname}</div>;
}
}
// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation);
个人写法:
import "../styles.css"
import routerList from '@/router/routerList'
import { withRouter } from "react-router" // 引入 withRouter
const Header = (props) =>{
const { history={}, } = props;
const go = (path) =>{
if(history.push){
history.push(path)
}
}
return <div className="header-warpper">
{routerList.map((item)=>{
const { path, } = item;
return <button key={path} onClick={()=>go(path)}>
{`go${path}`}
</button>
})}
</div>
}
const RouterHeader = withRouter(Header); // 使用 withRouter
export default RouterHeader;
报错:
二、解决办法
需要将BrowserRouter包裹到根节点上,子组件使用withRouter才会生效,不然即使不报错 参数也是获取不到的。
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { BrowserRouter } from 'react-router-dom'; // 引用
ReactDOM.render(
<React.StrictMode>
<BrowserRouter> // 包裹根组件
<App />
</BrowserRouter>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();