2017-03-08 98 views
0

我有2个文件jsx:不能/使用反应路由器

当我访问localhost:8080这是正常的。但是当我访问本地主机: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; 

回答

1

哟乌尔devServer配置,你需要的historyApiFallback设置:

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

这告诉devServer总是返回根html页面,让客户做路由。换句话说,要回滚到根api路由。

+0

嗨大卫·特赖恩。我加了,但是当我访问localhost:8080/home它显示在相同的结果localhost:8080。它不切换到主页。你可以帮我吗 ? –

+0

现在你有'IndexRoute'和'home'路线指向同一个地方。所以,你可能会得到相同的结果。尝试重新配置你的'路线'。 –

+0

渲染(( <路由器历史= {browserHistory}> <路由路径= “/” 成分= {应用}> \t <路由路径= “家” 成分= {主页} /> ),document.getElementById('app'));它不工作:( –

2

变化<Route path = "home" component = {Home} /><Route path = "/home" component = {Home} />

+0

它还没有工作,你有另一种方式吗? :( –