2017-02-23 26 views
0

React-Routerを使用してアプリケーション間で永続的なナビゲーションを作成しようとすると、問題が発生し、問題が発生する。私はちょうどリンクのカップルと、ページの上部にあるナビゲーションを持ってしようとしているcreate-react-app"react-router": "^3.0.2"永続ナビゲーションReact-Router

を使用して

。私は入れませんエラーがUncaught Error: <Link>s rendered outside of a router context cannot navigate.

index.jsです:ナビゲーション

import React from 'react'; 
import ReactDOM from 'react-dom'; 
import { browserHistory } from 'react-router'; 
import { Router, Route } from 'react-router'; 
import Routes from './routes'; 
import App from './components/App'; 
import './index.css'; 
import Navigation from './components/Navigation'; 

ReactDOM.render(
    <div> 
    <Navigation /> 
    <Routes history={browserHistory} /> 
    </div>, 
    document.getElementById('root') 
); 

/index.js

import React, { Component } from 'react'; 
import { Link } from 'react-router'; 

class Navigation extends Component { 
    render() { 
    return (
     <div> 
     <ul> 
      <li><Link to="about">About</Link></li> 
      <li><Link to="not-found">Not Found</Link></li> 
     </ul> 
     </div> 
    ); 
    } 
} 

export default Navigation; 

routes.js

import React from 'react'; 
import { Router, Route, IndexRoute, Link, browserHistory } from 'react-router'; 
import App from './components/App'; 
import About from './components/About'; 
import NotFound from './components/NotFound'; 
import Navigation from './components/Navigation'; 

const Routes = (props) => (
    <div> 
    <Router {...props}> 
     <Route path="/" component={App} /> 
     <Route path="/about" component={About}/> 
     <Route path="*" component={NotFound} /> 
    </Router> 
    </div> 
); 

export default Routes; 

URL(つまり、localhost:8080/about)でナビゲートし、正しいページを表示できます。しかし、ナビゲーションが正しく動作するようにする方法を理解することはできません。

答えて

0

あなたのindex.js

App

class App extends Component { 
    render() { 
    return (
     <div> 
     <Navigation /> 
     {this.props.children} 
     </div> 
    ); 
    } 
} 

のようなものを見て、あなたのルートが少なすぎるを変更する必要があるのではないあなたのAppコンポーネントの一部としてNavigationコンポーネントをレンダリングする必要があります。

<Router {...props}> 
    <Route path="/" component={App}> 
    {/* If you have a home page in your App component already, move it to a Home component */} 
    <IndexRoute component={Home} /> 
    <Route path="/about" component={About}/> 
    <Route path="*" component={NotFound} /> 
    </Route> 
</Router> 

リアクションルータは、サブルートからコンポーネントを親ルートに渡します。

たとえば、introduction examplesのドキュメントをご覧ください。

+0

これで私の頭を包み込むのが難しい時が来ました。アプリケーションは実際には私のIndexRouteでなければならず、内部に入れ子にされたアプリケーションは他のすべてのコンポーネントでなければなりませんか?そこで、NavigationでレンダリングされたAppを持っています。ここでAboutをクリックするとAboutコンポーネントがAppコンポーネント内にネストされてレンダリングされます。 –

+0

thats正しい、App内にレンダリングされたAbout(thatsは '{this.props.children}'のようになります)。 –

+0

実際には、私は自分の答えを編集しようとしています、ちょっとあなたのルートを少し変更する必要があることに気付きました... ... –