如何解决ReactJS中的页面刷新问题

时间:2019-03-24 16:45:25

标签: html reactjs routes

当我按F5键/刷新网页时,我在由Apache 2.2托管的react应用上收到404 not found错误

我正在运行带有react引导带和路由的reactjs

我已经看到在线ppl在公用文件夹中添加了一个.htaccess文件,然后构建了该应用程序,但这对我不起作用

import './App.css';
import { BrowserRouter as Router,
        Route,
        Link,
        Switch,
        Redirect
 } from 'react-router-dom';
import Home from './components/Home';
import Test from './components/Test';
import Test1 from './components/Test1';


class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Navbar />
        <Switch>
          <Route exact path="/" component={Home} />
          <Route exact path="/home" component={Home} />
          <Route exact path="/test" component={Test} />
          <Route exact path="/test1" component={Test1} />
          <Route component={NoMatch} />
        </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

2 个答案:

答案 0 :(得分:0)

我想当您不在根目录中时进行刷新。

我将此.htaccess文件用于我的应用,以使路由正常工作

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]

答案 1 :(得分:0)

我们遇到了这个问题,我们使用了以下设置:

<VirtualHost *:8080>
  ServerName example.com
  DocumentRoot /var/www/httpd/example.com

  <Directory "/var/www/httpd/example.com">
    ...

    RewriteEngine on
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    # Rewrite everything else to index.html to allow html5 state links
    RewriteRule ^ index.html [L]
  </Directory>
</VirtualHost>

我们从here获得了此配置。