2015-11-30 33 views
1

我遇到了一個情況,在我的應用程序識別索引路由的地方。我在我的app.js代碼如下所示:react-router只能進入索引路由

import React from 'react' 

import { render } from 'react-dom' 

import { Router, Route, Link, IndexRoute } from 'react-router' 

class App extends React.Component { 
    render() { 
     return (
      <div> 
      <div> 
       Hello There App 
      </div> 
      </div> 
     ); 
    } 
} 

class About extends React.Component { 
    render() { 
     return (
      <div> 
      <div> 
       Hello There About 
      </div> 
      </div> 
     ); 
    } 
} 

class Error extends React.Component { 
    render() { 
     return (
      <div> 
      <div> 
       Hello There Error 
      </div> 
      </div> 
     ); 
    } 
} 

React.render((
    <Router> 
    <Route path="/" component={App}> 
     <IndexRoute component={About}/> 
     <Route path="*" component={Error}/> 
    </Route> 
    </Router> 
), document.body) 

有一些類似的鏈接我檢查了: React Router only recognises index route

React router only works with root path

但這些並沒有推我沿。我運行一個Express服務器,我有一個路線有太多:

app.use(ecstatic({ root: __dirname + '/public', handleError:true })); 
app.get('/', function(request, response){ 
    response.sendfile("./public/index.html"); 
}); 

不管有沒有app.get("/"...我遇到同樣的問題。還值得注意的是,我也嘗試過這種方式:https://github.com/rackt/react-router但我的路線也沒有這樣工作。我將在這個問題上進行爲期4天的研究,希望你們中的一個能夠指引我朝着正確的方向前進。

的package.json:

"dependencies": { 
    "body-parser": "~1.14.1", 
    "browserify": "^10.2.6", 
    "cors": "^2.7.1", 
    "ecstatic": "~0.8.0", 
    "express": "~4.0.0", 
    "history": "^1.13.1", 
    "mongoose": "~4.2.6", 
    "react": "~0.13.3", 
    "react-dom": "^0.14.3", 
    "react-router": "^1.0.0", 
    "reactify": "^1.1.1", 
    "socket.io": "^1.3.7", 
    "uglify-js": "^2.4.24", 
    "watchify": "^3.2.3" 
    }, 
    "license": "public domain", 
    "devDependencies": { 
    "babelify": "^6.1.2" 
    } 

回答

2

讓你的路線是這樣的:

<Router> 
    <Route path="/" component={App}> 
    <IndexRoute component={Index}/> 
    <Route path="*" component={Error}/> 
    </Route> 
</Router> 

你缺少另一部分則是在您的應用程序組件,其嵌套的路徑組件應安裝{ this.props.children }

檢查出master-detail示例,其中使用NotFound路由。

你的服務器上我會重定向一切*不僅/到index.html的:

app.get('*', function(request, response){ 
    response.sendfile("./public/index.html"); 
}); 
+0

感謝您的答覆,我仍然得到同樣的問題。我去'http:// localhost:8000 /',然後將一些參數展示給URL http:// localhost:8000 /#/?_k = 3z6ymz,然後我將它帶到我的索引路徑上說'你好有應用程序',但是當我嘗試去'http:// localhost:8000/about'時,它將我帶到錯誤頁面(這是404.html)。如果我在我的server.js中將handleError設置爲false,它只是簡單地說不能獲得那個'about'路由。當我去'http:// localhost:8000 /#/ about'時,我看到'Hello There App'再加上一個參數'http:// localhost:8000 /#/ about?_k = de8di9' – doubleya

+1

你的幫助。這正是它的原因。我在路由中添加了'*',然後添加了'{this.props.children}'。另外,我在路線邏輯中稍微向後一點,所以感謝您清理所有問題! – doubleya