javascript 无法在构建React应用时看到该组件

pgx2nnw8  于 12个月前  发布在  Java
关注(0)|答案(2)|浏览(249)

我正在使用CoinGecko API构建一个cryptotracker应用程序。这是我的应用程序组件。

import Navbar from "./components/Navbar";
import Home from "./components/Home";
import { Route, Routes } from "react-router-dom";
import Show from "./components/Show";

function App() {
  return (
    <>
      <Navbar />
      <Routes>
        <Route index element={<Home />} />
        <Route path="/show" element={<Show />} />
      </Routes>
    </>
  );
}

export default App;

字符串
这是我的index.js文件:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>
);


这是我的导航栏组件:

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

function Navbar() {
  return (
    <>
      <div className="nav_container">
        <div className="nav">
          <div className="navigation_menu">
            <Link to="/" className="nav_heading">
              Coiner
            </Link>
            <ul>
              <li>Home</li>
              <li>Pricing</li>
              <li>Features</li>
              <li>About</li>
              <li>Contact</li>
            </ul>
          </div>
          <div className="nav_button">
            <button>Login</button>
          </div>
        </div>
      </div>
    </>
  );
}

export default Navbar;


这是我的家组件:

import React, { useEffect, useState } from "react";
import axios from "axios";
import Coin from "./Coin";
import Query from "./Query";

function Home() {
  const [coins, setCoins] = useState();
  const [query, setQuery] = useState("");
  const [components, setComponents] = useState(true);
  const [queryCoins, setQueryCoins] = useState();
  const [heading, setHeading] = useState("Trending Coins");
  useEffect(() => {
    window.scrollTo(0, 0);
    const getCoins = async () => {
      const response = await axios.get(
        "https://api.coingecko.com/api/v3/search/trending"
      );
      const result = response.data.coins;
      setCoins(result);
    };
    getCoins();
  }, []);
  const handleQueryChange = (event) => {
    const new_value = event.target.value;
    if (new_value === "") {
      setComponents(true);
      setHeading("Trending Coins");
    }
    setQuery(event.target.value);
  };
  const handleQuery = async () => {
    const response = await axios.get(
      `https://api.coingecko.com/api/v3/search?query=${query}`
    );
    const result = response.data.coins;
    setQueryCoins(result);
    setComponents(false);
    setHeading("Search Results");
  };
  const handleKeyChange = (event) => {
    if (event.key === "Enter") {
      handleQuery();
    }
  };
  return (
    <>
      <div className="outer_home_container">
        <div className="input_container">
          <input
            type="text"
            className="search_input"
            placeholder="Search for coins..."
            value={query}
            onChange={handleQueryChange}
            onKeyDown={handleKeyChange}
            maxLength={20}
          />
          <button onClick={handleQuery} className="input_button">
            <i className="fa-solid fa-magnifying-glass"></i>
          </button>
        </div>
        <h1>{heading}</h1>
        <div className="container">
          {components ? (
            coins ? (
              coins.map((key) => {
                return <Coin coin={key} key={key.item.id} />;
              })
            ) : (
              <h2>Loading...</h2>
            )
          ) : queryCoins ? (
            queryCoins.map((key) => {
              return <Query coin={key} key={key.id} />;
            })
          ) : (
            <h2>Loading...</h2>
          )}
        </div>
      </div>
    </>
  );
}

export default Home;


主要的问题是,当我通过npm run start运行我的应用程序时,它成功地渲染了所有组件,即Navbar和Home。但在我通过npm run build构建我的应用程序并通过live server运行网站后,它只渲染了Navbar组件,要渲染Home组件,我必须单击Coiner徽标,然后,只有这样,它才能成功地将Home组件和我的Navbar组件呈现在一起。
抱歉在格式上犯了任何错误,我是Stackoverflow Q& A的新手。
我尝试在构建应用程序之前编辑我的package.json文件。
代码如下:

{
  "name": "app",
  "homepage": "./",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "axios": "^1.6.3",
    "lodash": "^4.17.21",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.21.1",
    "react-scripts": "5.0.1",
    "recharts": "^2.10.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}


我把主页改成了“./”,但是没有用。
这是website's link
任何帮助将不胜感激。

2w2cym1i

2w2cym1i1#

请尝试使用HashRouter而不是BrowserRouterHashRouter使用URL的哈希部分来保持UI与URL同步。
替换index.js文件中的这一行:

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

字符串
使用:

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


并更改App的渲染:

root.render(
  <HashRouter>
    <App />
  </HashRouter>
);


package.json中设置homepage:将package.json中的homepage字段改回默认值(去掉./):

"homepage": "/",


为客户端路由配置服务器:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

jdgnovmf

jdgnovmf2#

如果你看一下你的网站的链接:
Page upon visiting
当你点击“Coiner”:
Page after clicking "Coiner"
你的仓库名消失了。这是因为React路由器dom重定向到索引路径名(即/)。此时,如果您尝试重新加载页面,Github页面将返回404状态。这是因为Github页面无法识别索引路径名/,但是你的React应用只在索引路径名/上渲染。页面内容在第一次访问时不渲染是因为React路由器无法识别路径名/Coiner-CoinGekoAPI/
您可以做的是将basename添加到您的BrowserRouter,即在您的index.js中:

import React from "react";
import ReactDOM from "react-dom/client";
import "./index.css";
import App from "./App";
import { BrowserRouter } from "react-router-dom";
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <BrowserRouter basename="/Coiner-CoinGekoAPI">
    <App />
  </BrowserRouter>
);

字符串
因此,您的整个应用程序将位于/Coiner-CoinGekoAPI
请注意,在开发中,您需要访问/Coiner-CoinGekoAPI而不是索引路径名/

相关问题