Persistent Navigation React

New to React and having troubles trying to create a persistent navigation across my application using React-Router.

Using the create-react-app and "react-router": "^3.0.2"

I'm trying to just have a Navigation on the top of the page with a couple of links. The error I keep getting is 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')
);

Navigation/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;

I can navigate by url (ie localhost:8080/about) and render the correct page. However cannot figure out how to get the Navigation to work and render the correct links.


You should render the Navigation component as part of your App component not in your index.js

App should look something like

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

And your routes need to change a little too.

<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>

React router will pass the components from subroutes as children to the parent route.

For example, check out the introduction examples in their documentation.

链接地址: http://www.djcxy.com/p/52134.html

上一篇: 如何在React Router v4中推送历史记录?

下一篇: 持续导航反应