没有刷新,React路由器将无法工作

时间:2017-09-06 12:54:02

标签: javascript reactjs routing redux

基本上,路径组件不会在点击改变路径的链接时触发;但刷新后,会显示正确的组件。什么可以解决这个问题?

应用程序组件:

import React, { Component } from 'react';
/**
 * Import Router
 */
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
/**
 * Import custom components
 */
import IndexComponent from '../components/index_component';
import LoginComponent from '../components/login_component';
/**
 * Import containers
 */
import Navbar from '../containers/Navbar';
import Footer from '../containers/Footer';

export default class App extends Component {
  render() {
    return (
        <div>
            <Navbar />
            <Router>
                <Switch>
                    <Route path="/login" component={LoginComponent} />
                    <Route path="/" component={IndexComponent} />
                </Switch>
            </Router>
            <Footer />
        </div>
    );
  }
}

登录组件:

import React, { Component } from 'react';

class LoginComponent extends Component {
    render() {
        return (
            <div>LOGIN COMP</div>
        );
    }
}

export default LoginComponent;

2 个答案:

答案 0 :(得分:0)

您应该将所有组件都包含在<Router>中,以解决您的问题。

<Router>
    <Navbar />
    <Switch>
        <Route path="/login" component={LoginComponent} />
        <Route path="/" component={IndexComponent} />
    </Switch>
    <Footer />
</Router>

答案 1 :(得分:0)

尝试以下解决方案:

   import React from 'react';
   import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
   import IndexComponent from '../components/index_component';
   import LoginComponent from '../components/login_component';


        <Router>
          <Switch>
             <Route path="/login" component={LoginComponent} />
            <Route path="/" component={IndexComponent} />
          </Switch>
        </Router>