'withRouter'未从'react-router-dom'中导出。

6
Failed to compile. Attempted import error: 'withRouter' is not exported from 'react-router-dom'.

我的代码类似如下,同时我已经安装了react-router-domreact-route,现在我已经重复运行了10次我的应用程序。

import React from 'react';
import {withRouter} from 'react-router-dom';

import './menu-item.scss';

const MenuItem = ({ title, imageUrl, size, history }) => (
  <div className={`${size} menu-item`}>
    <div
      className='background-image'
      style={{
        backgroundImage: `url(${imageUrl})`,
      }}
    />
    <div className='content'>
      <h1 className='title'>{title.toUpperCase()}</h1>
      <span className='subtitle'>SHOP NOW</span>
    </div>
  </div>
);

export default withRouter(MenuItem);

1
大声喊出来,类似于Switch(将会抛出相同的错误),这里是降级命令,只需确保您在正确的目录中 npm install react-router-dom@5.0.0 - Yusuf
5个回答

14
如果您意外安装了react-router-dom v6,则withRouter HOC不再存在。要么回滚到v5(运行npm install -s react-router-dom@5),要么创建自定义的withRouter HOC以注入所需的props,或将组件转换为函数组件并使用React hooks。

创建自定义的withRouter Higher Order Component

从常见问题解答中获取:withRouter发生了什么,我需要它
import {
  useLocation,
  useNavigate,
  useParams,
} from "react-router-dom";

function withRouter(Component) {
  function ComponentWithRouterProp(props) {
    let location = useLocation();
    let navigate = useNavigate();
    let params = useParams();
    return (
      <Component
        {...props}
        router={{ location, navigate, params }}
      />
    );
  }

  return ComponentWithRouterProp;
}

转换为函数组件

现在不再有可用的history对象,它被一个通过useNavigate hook访问的navigate函数所取代。目前还不清楚之前使用了history做了什么,但如果你需要进行命令式导航,下面是如何访问导航的方法。如果继续使用v6,则以下是访问navigate函数的方法。

import React from 'react';
import { useNavigate } from 'react-router-dom';

import './menu-item.scss';

const MenuItem = ({ title, imageUrl, size }) => {
  const navigate = useNavigate();

  // navigate("/targetPath")

  return (
    <div className={`${size} menu-item`}>
      <div
        className='background-image'
        style={{
          backgroundImage: `url(${imageUrl})`,
        }}
      />
      <div className='content'>
        <h1 className='title'>{title.toUpperCase()}</h1>
        <span className='subtitle'>SHOP NOW</span>
      </div>
    </div>
  )
};

export default MenuItem;

2
感谢Drew Reese的帮助,与Switch类似(会抛出相同的错误),这是降级命令,只需确保您在正确的目录中。
npm install react-router-dom@5.0.0

提供信息,截至今天看起来5.3.0是最新的v5.x版本,但v5.2.1已经稳定了很长时间。在我测试的codesandbox中似乎可以无问题运行。 - Drew Reese

2
您可以使用useLocation Hook,并从中析取'pathname'属性,使得onClick()函数中的导航链接具有动态性。
以下是我用过的代码示例:
  import React from "react";
  import { useLocation, useNavigate } from "react-router-dom";
  import "./menu-item.styles.scss";

  const MenuItem = ({ title, imageUrl, size, linkUrl, match }) => {
    let navigate = useNavigate();
    // destructured "pathname" property from useLocation()
    let { pathname } = useLocation();
    // consoloe.log(pathname)
    return (
      <div className={`${size} menu-item`} onClick={() => navigate(`${pathname}${linkUrl}`)}>
        <div
          className="background-image"
          style={{
            backgroundImage: `url(${imageUrl})`,
          }}
        />
        <div className="content">
          <h1 className="title">{title.toUpperCase()}</h1>
          <span className="subtitle">SHOP NOW</span>
        </div>
      </div>
    );
  };

  export default MenuItem;

1
menu-item.component.jsx 中,您可以像这样使用 useNavigate
import React from "react";
import { useNavigate } from "react-router-dom";

import "./menu-item.styles.scss";

const MenuItem = ({ title, imageUrl, size, history, linkUrl, match }) => {
  let navigate = useNavigate();
  return (
    <div className={`${size} menu-item`} onClick={() => navigate(`${linkUrl}`)}>
      <div
        className="background-image"
        style={{
          backgroundImage: `url(${imageUrl})`,
        }}
      ></div>

      <div className="content">
        <h1 className="title">{title.toUpperCase()}</h1>
        <span className="subtitle">SHOP NOW</span>
      </div>
    </div>
  );
};

export default MenuItem;

此外,在 App.js 中,您应该从 react-router-dom 导入 RoutesRoute,并使您的代码如下所示:

import React from "react";
import { Routes, Route } from "react-router-dom";

import "./App.css";
import HomePage from "./pages/homepage/homepage.component";

const HatsPage = () => (
  <div>
    <h1>Hats page</h1>
  </div>
);

function App() {
  return (
    <div>
      <Routes>
        <Route exact path="/" element={<HomePage />} />
        <Route path="/hats" element={<HatsPage />} />
      </Routes>
    </div>
  );
}

export default App;

就我而言,这个方法可行。


0

试试这个,对我有效

import React from "react";
import { useNavigate } from "react-router-dom";

import "./menu-item.styles.scss";

const MenuItem = ({ title, imageUrl, size, history, linkUrl, match }) => {
  const navigate = useNavigate();

  return (
    <div className={`${size} menu-item`} onClick={() => navigate(`hats`)}>
      <div
        className="background-image"
        style={{
          backgroundImage: `url(${imageUrl})`,
        }}
      ></div>

      <div className="content">
        <h1 className="title">{title.toUpperCase()}</h1>
        <span className="subtitle">SHOP NOW</span>
      </div>
    </div>
  );
};

export default MenuItem;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接