【问题标题】:Trouble with React Router in deploy部署中的 React Router 出现问题
【发布时间】:2020-05-11 00:43:38
【问题描述】:

我在尝试部署我的 react 应用程序时遇到了一些问题。在我的本地机器上,一切运行良好。但是,当我部署它时,当我手动输入链接或进行刷新时,链接不起作用。如果我点击页面上的按钮,它们确实可以工作

const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);

这是我的server.js,旨在让每个请求都转到index.html

<Router>
  <App />
</Router>

index.js 部分:

let content = (
    <Router>
      <div>
        <Header />
        <Switch>
          <Route path="/about-us/"><AboutUs/></Route>
           ...
          <Redirect from="/" to="/homepage/1"/>
          <Route ><PageNotFound /></Route>
        </Switch>
        <Footer />
      </div>
    </Router>
  )

  return (
    <div className='App'>
      {content}
    </div>
  );

还有我的 app.js

【问题讨论】:

  • 表示你没有实现服务端渲染。你使用 CRA 吗?

标签: reactjs react-router react-router-dom


【解决方案1】:

当我遇到这个问题时,我不得不添加历史记录。要解决此问题,请在 src 文件夹中创建文件 history.js,代码为

import { createBrowserHistory } from "history";

export default createBrowserHistory();

下一个yarn add historynpm install history

在您的app.js 文件中,您将import history from "./history" 并将history 添加到Router,如下所示:

let content = (
    <Router history={history}>
      <div>
        <Header />
        <Switch>
          <Route path="/about-us/"><AboutUs/></Route>
           ...
          <Redirect from="/" to="/homepage/1"/>
          <Route ><PageNotFound /></Route>
        </Switch>
        <Footer />
      </div>
    </Router>
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-18
    • 2017-03-17
    • 2020-07-29
    • 2015-12-12
    • 2016-01-22
    • 2020-10-22
    • 2017-09-10
    • 2017-11-14
    相关资源
    最近更新 更多