手动配置 react-router-dom时报错,You should not use withRouter(Home)

一、问题场景:

在组件中想使用函数式路由跳转,根据官方文档查到:需要在该组件导出时 使用 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();
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值