【问题标题】:React router V4 - Switch not rendering in productionReact router V4 - 在生产中切换不渲染
【发布时间】:2018-05-14 17:07:24
【问题描述】:

问题

在使用 react、react-router V4 和 webpack 构建我的生产项目时,“Switch”没有呈现任何匹配的路由。但它适用于开发环境。

我尝试过的

我在这里使用了样板:https://github.com/KleoPetroff/react-webpack-boilerplate

我的 Router.js 很简单:

import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import App from '../components/App';
import About from '../components/About';

const Root = () => {
return (
    <Router>
      <Switch>
        <Route path="/about" component={About} />
        <Route exact path="/" component={App} />
      </Switch>
    </Router>
);
};

export default Root;

而组件 App.js 和 About.js 很简单:

应用程序.js
import React from 'react';
import { Link } from 'react-router-dom';

const App = () => {
  return (
    <h2 id="heading">
      Hello ReactJS
      <Link to="/about">here</Link>
    </h2>
  );
};

export default App;
关于.js
import React from 'react';

const About = () => {
  return (
    <h2 id="heading">
      About ReactJS
    </h2>
  );
};

export default About;

我的研究

我经历了很多 stackoverflow 的类似问题(显然与 react-router-redux 更相关),但目前我没有得到有效的答案。

我尝试使用不同的 webpack 配置来实现应用程序,例如使用 react-create-app repo 的配置。

我不确定它是否与最新版本的 react-router 或我的 webpack 配置有关。

这听起来像是一个愚蠢而简单的问题,但我在网络上的任何地方都找不到答案。

所以我的问题是,如何让开关组件匹配正确的路径?

【问题讨论】:

  • 不渲染任何匹配的路由是什么意思?您是否得到完全白页,或者您的应用程序本身没有呈现路线?
  • 您可能需要配置您的网络服务器(检查下面的 asnwer),或者您可以使用 react-router 中的“HashRouter”。它不需要任何服务器配置。
  • 您好,谢谢您的回答,实际上我得到了一个完整的白页,因为似乎没有匹配的路线。如果我删除 path="/" 并执行基本的 ,它实际上会呈现组件。所以我相信路由器的默认位置在生产中是错误的。我也觉得跟webserver有关系,我只在本地尝试过,因为我以为会默认由webpack处理。

标签: javascript webpack react-router


【解决方案1】:

我最近遇到了类似的问题,并通过将所有请求解析回我的 .htaccess 文件中的 index.html 来解决它。

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

【讨论】:

  • 实际上我有这个想法,但我认为在我的构建文件夹中启动 index.html 时它会在本地工作(感谢 webpack ?)。我需要设置一个 apache 服务器来尝试它是否使用 .htaccess 文件工作。
  • 我尝试为我的 apache 服务器设置 .htaccess,现在它似乎已经纠正了这个问题。我会把答案标记为正确的。
  • 很高兴听到它解决了您的问题,如果您对此有任何其他问题,请告诉我。
猜你喜欢
  • 2018-02-10
  • 1970-01-01
  • 2019-01-15
  • 2018-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-18
相关资源
最近更新 更多