简体   繁体   English

useHistory:找不到模块:无法解析“react-router-dom”

[英]useHistory: Module not found: Can't resolve 'react-router-dom'

I have this project and this project is an ECommerce project, and in this project there is a Navbar, and in Navbar there are three items, "Home, Groups, Shopping", the problem is that when I click on "home" it takes me to the home page, and when it's done Clicking on "groups" will take me to the groups page, as well as for the shop我有这个项目,这个项目是一个电子商务项目,在这个项目中有一个导航栏,在导航栏中有三个项目,“主页,组,购物”,问题是当我点击“主页”时它需要我到主页,完成后点击“组”将带我到组页面,以及商店

And for this thing, I used usehistory and对于这件事,我使用了 usehistory 和

"import { useHistory } from "react-router-dom";"

but I got this error:但我收到了这个错误:

Module not found: Can't resolve 'react-router-dom'

I also used this instruction我也使用了这个指令

"import { useHistory } from "react-router";" 

and got this error:并得到这个错误:

Module not found: Can't resolve 'react-router-dom'

How can I solve the problem?我该如何解决这个问题?

package.json:包.json:

{
  "name": "c-cart-front-end",
  "version": "1.0.0",
  "description": "",
  "private": true,
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "next"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@apollo/client": "^3.5.6",
    "@apollo/react-ssr": "3.0.0",
    "@firebase/app": "^0.6.18",
    "@types/react-slick": "^0.23.4",
    "@types/react-sticky-el": "^1.0.2",
    "@types/reactstrap": "^8.4.1",
    "@zeit/next-css": "^1.0.1",
    "@zeit/next-sass": "^1.0.1",
    "@zeit/next-typescript": "^1.1.1",
    "animate.css": "^3.7.2",
    "apollo-boost": "^0.4.7",
    "bootstrap-scss": "^4.4.1",
    "deepmerge": "^4.2.2",
    "firebase": "^8.3.2",
    "graphql": "^14.6.0",
    "i18next": "^19.3.4",
    "i18next-browser-languagedetector": "^4.0.2",
    "isomorphic-unfetch": "^3.0.0",
    "jimp": "^0.9.3",
    "js-cookie": "^3.0.1",
    "next": "^12.0.4-canary.4",
    "next-compose-plugins": "^2.2.0",
    "next-fonts": "^1.0.3",
    "next-images": "^1.8.4",
    "nprogress": "^0.2.0",
    "react": "^17.0.2",
    "react-apexcharts": "^1.3.9",
    "react-content-loader": "^5.0.1",
    "react-countdown": "^2.3.1",
    "react-dom": "^17.0.2",
    "react-fullpage": "^0.1.19",
    "react-helmet": "^6.1.0",
    "react-helmet-async": "^1.2.2",
    "react-hook-form": "^6.8.6",
    "react-i18next": "^11.3.4",
    "react-image": "^2.2.2",
    "react-image-lightbox": "^5.1.1",
    "react-input-range": "^1.3.0",
    "react-intl": "^4.3.1",
    "react-masonry-css": "^1.0.14",
    "react-messenger-customer-chat": "^0.8.0",
    "react-multi-carousel": "^2.5.0",
    "react-paypal-button": "^4.1.1",
    "react-responsive-carousel": "^3.1.51",
    "react-reveal": "^1.2.2",
    "react-slick": "^0.25.2",
    "react-sticky-el": "^1.1.0",
    "react-tabs": "^3.1.2",
    "react-toastify": "^5.5.0",
    "reactstrap": "^8.4.1",
    "responsive-loader": "^1.2.0",
    "rxjs-compat": "^6.5.4",
    "sass": "^1.45.1"
  }
}

This file contains the navbar in the project with the elements inside it该文件包含项目中的导航栏,其中包含元素

import React, { useState, useEffect } from "react";
import Link from "next/link";
import { MENUITEMS } from "../../constant/menu";
import { Container, Row } from "reactstrap";
import { useTranslation } from "react-i18next";
import { useRouter } from "next/router";
import { useHistory } from "react-router";

const NavBar = () => {
  const history = useHistory();
  const { t } = useTranslation();
  const [navClose, setNavClose] = useState({ right: "0px" });
  const router = useRouter();

  useEffect(() => {
    if (window.innerWidth < 750) {
      setNavClose({ right: "-410px" });
    }
    if (window.innerWidth < 1199) {
      setNavClose({ right: "-300px" });
    }
  }, []);

  const openNav = () => {
    setNavClose({ right: "0px" });
    if (router.asPath == "/layouts/Gym")
      document.querySelector("#topHeader").classList.add("zindex-class");
  };

  const closeNav = () => {
    setNavClose({ right: "-410px" });
    if (router.asPath == "/layouts/Gym")
      document.querySelector("#topHeader").classList.remove("zindex-class");
  };

  const [mainmenu, setMainMenu] = useState(MENUITEMS);

  useEffect(() => {
    const currentUrl = location.pathname;
    MENUITEMS.filter((items) => {
      if (items.path === currentUrl) setNavActive(items);
      if (!items.children) return false;
      items.children.filter((subItems) => {
        if (subItems.path === currentUrl) setNavActive(subItems);
        if (!subItems.children) return false;
        subItems.children.filter((subSubItems) => {
          if (subSubItems.path === currentUrl) setNavActive(subSubItems);
        });
      });
    });
  }, []);

  const setNavActive = (item) => {
    MENUITEMS.filter((menuItem) => {
      if (menuItem != item) menuItem.active = false;
      if (menuItem.children && menuItem.children.includes(item))
        menuItem.active = true;
      if (menuItem.children) {
        menuItem.children.filter((submenuItems) => {
          if (submenuItems.children && submenuItems.children.includes(item)) {
            menuItem.active = true;
            submenuItems.active = false;
          }
        });
      }
    });

    setMainMenu({ mainmenu: MENUITEMS });
  };

  const status = (title) => {
    switch (title) {
      case "home":
        return "http://localhost:3000";
      case "collections":
        return "/page/collection";

      default:
        return "http://localhost:3000";
    }
  };

  function handleClickHome() {
    history.push("http://localhost:3000");
  }

  function handleClickCollections() {
    history.push("/page/collection");
  }

  function handleClickShops() {
    history.push("/page/collection");
  }

  return (
    <div>
      <div className="main-navbar">
        <div id="mainnav">
          <div className="toggle-nav" onClick={openNav.bind(this)}>
            <i className="fa fa-bars sidebar-bar"></i>
          </div>
          <ul className="nav-menu" style={navClose}>
            <li className="back-btn" onClick={closeNav.bind(this)}>
              <div className="mobile-back text-right">
                <span>Back navbar</span>
                <i className="fa fa-angle-right pl-2" aria-hidden="true"></i>
              </div>
            </li>
            {/* {MENUITEMS.map((menuItem, i) => { */}
            {/* return ( */}
            <li
            // key={i}
            // className={` ${menuItem.megaMenu ? "mega-menu" : ""}`}
            >
              {/* <a className="nav-link" onClick={(e) => console.log("Hi")}>
                    {" "}
                    {t(menuItem.title)}
                  </a> */}
              <a
                className="nav-link"
                style={{ color: "red" }}
                onClick={handleClickHome}
              >
                {" "}
                {t("Home")}
              </a>
            </li>

            <li>
              <a className="nav-link" onClick={handleClickShops}>
                {" "}
                {t("Shop")}
              </a>
            </li>
            <li>
              <a className="nav-link" onClick={handleClickCollections}>
                {" "}
                {t("Collections")}
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );
};

export default NavBar;

I solved the problem through these instructions:我通过这些说明解决了这个问题:

import { useRouter } from "next/router";

const router = useRouter();

  function handleClickHome() {
    router.push("http://localhost:3000");
  }

  function handleClickCollections() {
    router.push("/page/collection");
  }

  function handleClickShops() {
    router.push("/page/collection");
  }


 return (
    <div>
      <div className="main-navbar">
        <div id="mainnav">
          <div className="toggle-nav" onClick={openNav.bind(this)}>
            <i className="fa fa-bars sidebar-bar"></i>
          </div>
          <ul className="nav-menu" style={navClose}>
            <li className="back-btn" onClick={closeNav.bind(this)}>
              <div className="mobile-back text-right">
                <span>Back navbar</span>
                <i className="fa fa-angle-right pl-2" aria-hidden="true"></i>
              </div>
            </li>
            <li>
              <a
                className="nav-link"
                style={{ color: "red" }}
                onClick={handleClickHome}
              >
                {" "}
                {t("Home")}
              </a>
            </li>

            <li>
              <a className="nav-link" onClick={handleClickShops}>
                {" "}
                {t("Shop")}
              </a>
            </li>
            <li>
              <a className="nav-link" onClick={handleClickCollections}>
                {" "}
                {t("Collections")}
              </a>
            </li>
          </ul>
        </div>
      </div>
    </div>
  );

Well, just like the error says, you don't have react-router-dom installed.好吧,就像错误所说的那样,您没有安装 react-router-dom。 Just run npm install --save react-router-dom .只需运行npm install --save react-router-dom

You also need to use:您还需要使用:

import { useHistory } from "react-router-dom";

I think your react-router-dom package module is v6 if you install at the moment, so you have to use useNavigate instead of useHistory , see more: useNavigate() in react-router v6我认为如果你现在安装你的 react-router-dom 包模块是 v6,所以你必须使用useNavigate而不是useHistory ,查看更多: useNavigate() in react-router v6

// This is a React Router v6 app
import { useNavigate } from "react-router-dom";

function App() {
  let navigate = useNavigate();
  function handleClick() {
    navigate("/home");
  }
  return (
    <div>
      <button onClick={handleClick}>go home</button>
    </div>
  );
}

'useHistory' is depreciated in V6 of react-router. 'useHistory' 在 react-router 的 V6 中被贬低。 You can use 'useNavigate' or 'Navigate' for doing the same thing.您可以使用“useNavigate”或“Navigate”来做同样的事情。

if you use 'useNavigate' the code would be--如果您使用“useNavigate”,代码将是——

import { useNavigate } from 'react-router-dom'
const FileName = () => {
return (
<>
const navigate = useNavigate();
<li  
   onClick={()=>{navigate("/path");}}>
      'link-name'        
 </li> 
 </> 
  )
}

And if you use 'Navigate' the code would be--如果您使用“导航”,代码将是——

import { Navigate } from 'react-router-dom';
const FileName= () => {

const[goToHome, setGoToHome] = React.useState(false);
if(goToHome){
return <Navigate to = "/Home" />;
}
return (
<>
<li 
 onClick={()=>{setGoToHome(true);}}>
   Home
</li >
</> 
 )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM