ReactJS: 404 error on reloading the inner componen

2019-08-30 18:25发布

问题:

I am getting 404 error every time I am reloading any inner component. I always have to navigate to home page and then reload/refresh the page for the application to work again.

I have tried using the BrowserRouter but that didn't work either.

Here is my code:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import { Router, Route, Switch } from "react-router-dom";

const history = createBrowserHistory();

/** elements */
import Header from './components/elements/Header';
import Footer from './components/elements/Footer';

/** components */
import Projects from './components/Projects';
import ProjectsAdd from './components/ProjectsAdd';
import Categories from './components/Categories';
import CategoriesAdd from './components/CategoriesAdd';

export default class Index extends Component
{
  render()
  {
    return (
      <Router history={history}>
        <div id="main">
          <Header />

          <section className="content">
            <section id="pageRight">
              <Switch>
                <Route exact path={"/"} component={Projects} />
                <Route path={"/projects/add"} component={ProjectsAdd} />

                <Route exact path={"/categories"} component={Categories} />
                <Route path={"/categories/add"} component={CategoriesAdd} />
              </Switch>
            </section>
          </section>

          <Footer />
        </div>
      </Router>
    );
  }
}

if (document.getElementById('layout'))
  ReactDOM.render(<Index />, document.getElementById('layout'));

回答1:

I found the solution (https://youtu.be/vNof0z32l84).

I hope this may come in handy for someone. However, If you feel there is a room for improvement then please let me know. :)