Navlink - React Router Dom 在 React.Js 中不工作

Navlink - React Router Dom not working in React.Js

我正在使用 redux 和 react。我的导航菜单上有一个地图方法,我想使用 Navlink 导航到 /products - react router v5.2。但是当我点击 shop link 按钮时,它会转到产品页面,但我再次点击我的徽标并返回主页,然后我再次点击 shop link 按钮然后它不会导航。我的代码有什么问题?下面附上代码和截图供大家参考。

import React, { useEffect, useState } from "react";
import "./header.css";
import { useDispatch, useSelector } from "react-redux";
import { setHeaderData } from "../../redux/actions/header-actions/HeaderActions";
import { setBgColor } from "../../redux/actions/header-actions/HeaderActions";
import Loading from "../other/loading/Loading";
import PageNotFound from "../other/page-not-found/PageNotFound";
import { NavLink } from "react-router-dom";

const Header = () => {
  const [isLoading, setIsLoading] = useState(true);
  const headerData = useSelector((state) => state.header.headerData);
  const bgColor = useSelector((state) => state.header.bgColor);
  const { bgColour, borderColor, iconColor } = bgColor;
  const dispatch = useDispatch();

  useEffect(() => {
    // get header data
    getHeaderData();

    // send object for changing bg colour
    window.addEventListener("scroll", () => {
      changeNavBg({
        bgColour: "bg-black",
        borderColor: "border-white",
        iconColor: "text-white",
      });
    });

    return () => {
      // remove changeNavBg event on scroll
      window.removeEventListener("scroll", changeNavBg);
    };
  }, []);

  // change nav bg colour on scroll
  const changeNavBg = (bgColor) => {
    if (window.scrollY > 0) {
      dispatch(setBgColor(bgColor));
    } else {
      dispatch(
        setBgColor({
          bgColour: "bg-transparent",
          borderColor: "",
          iconColor: "",
        })
      );
    }
  };

  // get header data
  const getHeaderData = async () => {
    try {
      const response = await fetch("http://localhost:8000/navLinks");
      const data = await response.json();
      if (data) {
        setIsLoading(false);
        dispatch(setHeaderData(data));
      } else {
        setIsLoading(true);
      }
    } catch (error) {
      console.log(error);
    }
  };

  // if loading is true return Loading
  if (isLoading) {
    return <Loading loadingHeader={"header"} />;
  }

  // console.log(bgColor);

  return (
    <>
      {headerData ? (
        <div className="dvHeader">
          <nav
            className={`navbar navbar-expand-lg ${bgColour} navbar-light fixed-top`}
          >
            <div className="container">
              <div>
                <button
                  className="navbar-toggler"
                  type="button"
                  data-toggle="collapse"
                  data-target="#slideDownMenu"
                  aria-controls="slideDownMenu"
                  aria-expanded="false"
                  aria-label="Toggle navigation"
                >
                  <span className="">
                    <i className={`fa fa-bars ${iconColor}`}></i>
                  </span>
                </button>
              </div>
              <div className="order-lg-0">
                <NavLink to="/">
                  <img
                    width="50"
                    src={headerData.logo.url}
                    className="img-fluid"
                    alt=""
                  />
                </NavLink>
              </div>
              <div className="order-lg-2 d-lg-none">
                <span
                  className="d-flex"
                  data-toggle="modal"
                  data-target="#mobileCartModal"
                >
                  <span className="d-inline-block mr-1">
                    <i className={`fa fa-shopping-cart ${iconColor}`}></i>
                  </span>
                  <span className={`d-inline-block ${iconColor}`}>0</span>
                </span>
              </div>
              <div
                className="collapse navbar-collapse order-lg-1"
                id="slideDownMenu"
              >
                <ul className="navbar-nav mr-auto px-3">
                  {headerData.parentLinks &&
                    headerData.parentLinks.map((parentLink) => {
                      const { id, link, subLinks } = parentLink;
                      return (
                        <li key={id} className="nav-item dropdown">
                          <NavLink
                            className={
                              id !== 2 ? "nav-link" : "nav-link dropdown-toggle"
                            }
                            to={id === 1 ? "/products" : ""}
                            id="navbarDropdown"
                            role="button"
                            data-toggle="dropdown"
                            aria-haspopup="true"
                            aria-expanded="false"
                          >
                            {link}
                          </NavLink>
                          <div
                            className={id === 2 ? "dropdown-menu" : "d-none"}
                            aria-labelledby="navbarDropdown"
                          >
                            {subLinks &&
                              subLinks.map((subLink) => {
                                const { id, link } = subLink;
                                return (
                                  <a
                                    key={id}
                                    className="dropdown-item"
                                    href="#"
                                  >
                                    {link}
                                  </a>
                                );
                              })}
                          </div>
                        </li>
                      );
                    })}
                </ul>
                <form className="dvSearch my-2 my-lg-0 px-3">
                  <input
                    className={`form-control border-top-0 border-right-0 border-left-0 mr-sm-2 ${
                      window.innerWidth > 991 ? borderColor : ""
                    }`}
                    type="text"
                    placeholder="Search"
                    aria-label="Search"
                  />
                  <button className="btn my-2 my-sm-0" type="submit">
                    <i className={`fa fa-search ${iconColor}`}></i>
                  </button>
                </form>
              </div>
            </div>
          </nav>
        </div>
      ) : (
        <PageNotFound />
      )}
    </>
  );
};

export default Header;

APP.JS

import React from "react";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import Homepage from "./containers/home-page/index";
import Header from "./containers/header/Header";
import Footer from "./containers/footer/Footer";
import ProductListing from "./containers/products/product-list/ProductList";
import ProductDetail from "./containers/products/product-detail/ProductDetail";
import PageNotFound from "./containers/other/page-not-found/PageNotFound";
import Account from "./containers/account/index";
import Checkout from "./containers/checkout/Index";
import LoginModal from "./containers/auth/modal/login-modal/LoginModal";
import SignupModal from "./containers/auth/modal/signup-modal/SignupModal";
import MobileCartModal from "./containers/products/mobile-cart-modal/MobileCartModal";

const App = () => {
  return (
    <>
      <BrowserRouter>
        <Header />
        <Switch>
          <Route path="/" exact component={Homepage} />
          <Route path="/products" exact component={ProductListing} />
          <Route path="/productdetail" exact component={ProductDetail} />
          <Route path="/checkout" exact component={Checkout} />
          <Route path="/account" exact component={Account} />
          <Route path="*" component={PageNotFound} />
        </Switch>
        <Footer />
        <LoginModal />
        <SignupModal />
        <MobileCartModal />
      </BrowserRouter>
    </>
  );
};

export default App;

DB.JSON

"navLinks": {
    "logo": {
      "url": "LOGO"
    },
    "parentLinks": [
      {
        "id": 1,
        "link": "Shop"
      },
      {
        "id": 2,
        "link": "Learn",
        "subLinks": [
          { "id": 1, "link": "Process" },
          { "id": 2, "link": "About Us" },
          { "id": 3, "link": "Blog" },
          { "id": 4, "link": "News" },
          { "id": 5, "link": "Beyond The Bottle" }
        ]
      },
      { "id": 3, "link": "Sign Up" },
      { "id": 4, "link": "Login" }
    ]
  }

我找到了答案。当 id 为 1 时,我删除了 bootstrap 属性“data-toggle”。检查下面的代码,它现在可以正常工作了。 Bootstrap 切换属性导致了问题。

<NavLink
   className={
    id !== 2 ? "nav-link" : "nav-link dropdown-toggle"
    }
   to={id === 1 ? "/products" : ""}
   id="navbarDropdown"
   role="button"
   // removed bootstrap attribute
   data-toggle={id !== 1 ? "dropdown" : ""}
   aria-haspopup="true"
   aria-expanded="false"
 >
   {link}
</NavLink>