Reactjs路由器无法获取/ page

时间:2019-08-28 18:34:21

标签: reactjs react-router

我面对reactjs的尴尬问题。这是关于路由。当路由到任何页面时,它确实很棒!唯一的问题,当我重新加载页面时,它会触发此Cannot GET /employee,这里员工是我的页面名称!

我不明白为什么要看到这个。

这是我的index.js文件:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom'

import App from "../client/components/App";

import { Provider } from 'react-redux'

import { createStore } from 'redux'
import postReducer from '../client/postReducer'

const store = createStore(postReducer)


// if we don't subcribe, yet our crud operation will work
function onStateChange() {
  const state = store.getState();
}

store.subscribe(onStateChange)

ReactDOM.render((
  <BrowserRouter>
      <Provider store={store}>
        <App />
      </Provider>
  </BrowserRouter>
), document.getElementById('app'))

这是我的app.js文件

import React, { Component } from 'react';
import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom';
import Home from '../components/home';
import Contacts from '../components/contact';
import About from '../components/about';
import Employees from '../components/Employees';

class App extends Component {
  render() {
    return (
    <Router>
        <div className="container">
          <nav className="navbar navbar-expand-lg navbar-light bg-light">
          <ul className="navbar-nav mr-auto">
            <li><Link to={'/'} className="nav-link"> Home </Link></li>
            <li><Link to={'/employee'} className="nav-link">Employee</Link></li>
            <li><Link to={'/contact'} className="nav-link">Contact</Link></li>
            <li><Link to={'/about'} className="nav-link">About</Link></li>
          </ul>
          </nav>
          <hr />
          <Switch>
              <Route exact path='/' component={Home} />
              <Route path='/employee' component={Employees} />
              <Route path='/contact' component={Contacts} />
              <Route path='/about' component={About} />
          </Switch>
        </div>
      </Router>
    );
  }
}

export default App;

这是我的webpack

const merge = require('webpack-merge');
const common = require('./webpack.common.js');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './dist'
  }
});

任何人都可以帮助我解决此错误Cannot GET /employee吗?

1 个答案:

答案 0 :(得分:1)

我认为这与以下内容重复:react routing and django url conflict

  

问题可能是您尚未配置要处理的URL   在React Router中定义的路由。在您的Django urls.py中   您应该使用catch all来将所有URL匹配到索引   模板

urlpatterns += [
    # match the root
    url(r'^$', base_view),
    # match all other pages
    url(r'^(?:.*)/?$', base_view),
]
     

base_view是一个视图函数,可呈现一个模板,   包括您捆绑的应用。

但是,您不应该使用django来提供静态文件,因为它不是为django设计的,因此执行效果也不佳?。一种快速的选择是集成django whitenoise,但是最佳实践是使用Web服务器,例如nginx,甚至更好的CDN。您可以在github pages上免费托管静态文件,例如react bundle app,这也很好。