简体   繁体   English

锚链接在本地工作但在部署时不工作 (React)

[英]Anchor links working locally but not when deployed (React)

I have a one page react app and I have a menu with anchor links set up like this:我有一个单页的 React 应用程序,我有一个带有锚链接的菜单,设置如下:

<a href="/App#story" class="font-medium text-gray-100 hover:text-red-600">Story</a>

And in the target div, I have it like this:在目标 div 中,我是这样的:

<div id="story" class="py-16 xl:py-36 px-4 sm:px-6 lg:px-8 bg-black overflow-hidden">

When I do npm start to run the page locally, the anchor links work as intended.当我执行npm start在本地运行页面时,锚链接按预期工作。 When I deploy it to the web, the links give me a 404.当我将它部署到网络时,这些链接给了我一个 404。

Why would this happen?为什么会发生这种情况?

As far as I am aware you can not use <a> tags for internal navigation in react.据我所知,您不能在<a>使用<a>标签进行内部导航。 I don't know why it works locally for you.我不知道为什么它在本地对你有用。

With react you are creating single page applications (SPAs), you have 1 html page that can be found in the public folder.使用 react 创建单页应用程序 (SPA),您可以在公共文件夹中找到 1 个 html 页面。 If you created the app using create-react-app , you will see within it, an element such <div id=root> </div> .如果您使用create-react-app ,您将在其中看到一个元素,例如<div id=root> </div> That is the targetted rendering location, where you will be rendering the entire app by dynamically changing the html within it as you interact with the page.那是目标渲染位置,您将在该位置通过在与页面交互时动态更改其中的 html 来渲染整个应用程序。

However, when you typically click on an <a> tag, we are usually taken to different html page.但是,当您通常单击<a>标签时,我们通常会被带到不同的 html 页面。 Here I would assume the server is trying to retrieve either the App.html page or index.html page from within public/App folder.在这里,我假设服务器正在尝试从 public/App 文件夹中检索 App.html 页面或 index.html 页面。

React does not typically come in with built in routing functions/components. React 通常没有内置路由功能/组件。 It leaves it up to the user to implement.它留给用户来实现。 So user's usually turn to a package like react-router along with react-router-dom/native (depending on react or react native) to get those functionalities.所以用户通常会转向像react-router这样的包以及react-router-dom/native (取决于 react 或 react native)来获得这些功能。

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

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