【问题标题】:create-react-app and react-router routes not working correctly in S3create-react-app 和 react-router 路由在 S3 中无法正常工作
【发布时间】:2019-12-11 22:38:56
【问题描述】:

我已经使用 npm run build 构建了我的应用程序并将构建上传到 S3,但无法完全正确地获取路线。

路线在开发中工作,但在构建和上传后停止。我也可以在本地提供服务,但在 S3 上它会停止。

这是本地的工作原理

<Route path="/" exact component={HomeView} />
<Route path="/home" component={HomeView} />

我可以让它在 S3 中(某种程度上)工作的唯一方法是使用 /*

<Route path="/" exact component={HomeView} />
<Route path="/*" exact component={HomeView} />
<Route path="/home" component={HomeView} />

/* 的问题是每条路由上面都有主页。因此,两条路线都堆叠在一起。但是,在第一次设置中,什么都没有显示,如果我检查页面,根元素是空的。 Index.js 仍会加载,因为背景会根据其加载的样式更改颜色。似乎 react-router 没有得到正确的路由。

S3 存储桶设置为指向 index.html。我确信这个问题可能很容易解决,但这是我对 react-router 的误解。

【问题讨论】:

    标签: reactjs amazon-web-services amazon-s3 react-router


    【解决方案1】:

    这就是我在尝试了很多事情后得到它的方式:

    <Route path="/*" component={() => <Redirect to='/home' />} />
    

    一个新问题是你登陆 index.html ,它将你的 url 重定向到 www.mydomain.com/home 并且一切看起来都很好。但是,如果您将该链接提供给某人,他们会收到错误消息。 IE。如果我复制 url 并将其粘贴到新选项卡中,我会收到错误消息。它似乎只有在您首先导航到 www.mydomain.com/index.html 并让 react-router 接管时才有效。

    【讨论】:

      【解决方案2】:

      我使用HashRouter 解决了类似的问题。

      import { Switch, Route, HashRouter } from 'react-router-dom';
      
      const App = () => (
          <HashRouter>
              <div>
                  <NavBar/>
                  <Switch>
                      <Route exact path="/projects" component={Projects}/>
                      <Route exact path="/about" component={About}/>
                      <Route component={NoMatch}/>
                  </Switch>
              </div>
          </HashRouter>
      );
      

      应用程序可以通过类似的方式访问 https://your-domain.s3.amazonaws.com/index.html?someParam=foo&amp;otherPram=bar/#/projects

      在本地主机上 https://localhost:3000/?someParam=foo&amp;otherPram=bar/#/projects

      不需要对 S3 进行任何更改。

      【讨论】:

        猜你喜欢
        • 2021-02-18
        • 2023-02-05
        • 2022-12-04
        • 2018-02-06
        • 2018-08-21
        • 2020-02-04
        • 2020-08-31
        • 1970-01-01
        • 2019-03-18
        相关资源
        最近更新 更多