无法获得/使用React Router

时间:2017-03-08 08:38:54

标签: javascript reactjs

我有两个文件jsx:

当我访问localhost时:8080这是正常的。但当我访问localhost时:8080 / home它在浏览器中显示消息无法获取/回家

我该如何解决?

Home.jsx

import React from 'react';


class Home extends React.Component{

    constructor(props) {
        super(props);

    }

    render(){

        return(
            <div>
                <h1>Home ...</h1>
            </div>

        )
    }
}
export default Home;

index.jsx:

import React from 'react';
import {render} from 'react-dom';
import Home from './Home.jsx';
import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router';



class App extends React.Component {

    render(){
        return(
            <div>
                <ul>
                     <li>Home</li>
                 </ul>
                 {this.props.children}
            </div>
        );
    }


}

render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />

      </Route>
   </Router>

), document.getElementById('app'));

文件webpack.config.js:

var webpack = require('webpack');
var path = require('path');

var BUILD_DIR = path.resolve(__dirname, 'src/client/public');
var APP_DIR = path.resolve(__dirname, 'src/client/app');

var config = {
    entry: APP_DIR + '/index.jsx',
  output: {
    path: BUILD_DIR,
    filename: 'bundle.js'
  },
  devServer: {
      inline: true,
      port: 8080,
    contentBase: "./src/client",

    hot: true
   },
  module : {
    loaders : [
      {
        test : /\.jsx?/,
        include : APP_DIR,
        loader : 'babel-loader',
        query: {
               presets: ['es2015', 'react']
            }
      }
    ]
  }
};

module.exports = config;

2 个答案:

答案 0 :(得分:2)

devServer配置中,您需要historyApiFallback设置:

   devServer: {
      inline: true,
      port: 8080,
      contentBase: "./src/client",
      historyApiFallback: true,
      hot: true
   },

这告诉devServer始终返回根html页面并让客户端进行路由。换句话说,回退到根api路由。

答案 1 :(得分:2)

<Route path = "home" component = {Home} />更改为<Route path = "/home" component = {Home} />