为什么在构建后不工作 react-router-dom? [英] why don't work react-router-dom after build?

查看:35
本文介绍了为什么在构建后不工作 react-router-dom?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

链接在构建后不起作用,但在 localhost:3000 中有效

我使用 react-router-dom 组件

构建项目:

npm 运行构建

app.js:

 返回 (<div><路由器><标题/><路由精确路径="/" component={Home}/><Route path="/about" component={About}/><Route path="/join" component={Join}/><Route path="/advertisement" component={Advertisement}/><Route path="/contact" component={Contact}/><Route path="/details" component={Details}/></路由器>

);}

和其他组件中的链接:

    <li><Link to='/'>home</Link></li><li><Link to='/about'>关于我们</Link></li><li><Link to='/join'>join</Link></li><li><Link to='/advertisement'>广告</Link></li><li><Link to='/contact'>联系我们</Link></li>

package.json

"主页": ".",

解决方案

这种情况背后有一个非常特定的原因.

第一个解决方案:react 是单页应用程序,因此当您构建应用程序时,服务器只知道 index.html,因此对于任何其他 url 你将不得不 configure server for fallback mechanism to index.html 并且在 react 应用程序将负责 url 处理.

第二种解决方案:如果您使用 hash router,则不会出现此问题.
使用哈希路由器的原因是了解有关哈希路由器及其用例的更多信息

import { HashRouter as Router, Route, Switch } from "react-router-dom"

links doesn't work after being build but it works in localhost:3000

I use react-router-dom component

build project with :

npm run build

app.js:

    return (  
      <div>
        <Router >
          <Header/>
              <Route exact path="/" component={Home}/>
              <Route path="/about" component={About}/>
              <Route path="/join" component={Join}/>
              <Route path="/advertisement" component={Advertisement}/>
              <Route path="/contact" component={Contact}/>
              <Route path="/details" component={Details}/>

        </Router>
      </div>
    );
  }

and links in other components:

<ul>
    <li><Link to='/'>home</Link></li>
    <li><Link to='/about'>about us</Link></li>
    <li><Link to='/join'>join</Link></li>
    <li><Link to='/advertisement'>ads</Link></li>
    <li><Link to='/contact'>contact us</Link></li>
</ul>

package.json

"homepage": ".",

解决方案

There is a very specific reason behind this scenario.

1st solution : react is a single page application so when you have build the application , server know only about index.html so for any other url you will have to configure server for fallback mechanism to index.html and after react app will take care of url handling.

2nd solution: if you use hash router than this issue will not occur.
the reason behind using hash router is know more about hashrouter and it's use cases

import { HashRouter as Router, Route, Switch } from "react-router-dom" 

这篇关于为什么在构建后不工作 react-router-dom?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆