简体   繁体   中英

Router history with react-router 4.0.0

In react-router 4.0.0 the history provisoning seems to have changed, with the following index.js

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

ReactDOM.render(
  <Router history={hashHistory}>
    <Route path="/" component={App} />
  </Router>, document.getElementById('root')
);

I get:

Warning: Failed prop type: The prop `history` is marked as required in `Router`, but its value is `undefined`.

and an error afterwards. I browsed the code but can't find any example or API how that has changed.

React Router v4 changed things little bit. They made separate top level router elements. Replace <Router history={hashHistory}> with <HashRouter> in your code.

Hope this will help full.

import {HashRouter,Route} from 'react-router-dom';

<HashRouter>
    <Route path = "/getapp" component = {MainApp} />
</HashRouter>

hashHistory is no longer an exported object of react-router . If you want to use a hash history, you can just render a <HashRouter> .

import { HashRouter } from 'react-router-dom'

ReactDOM.render((
  <HashRouter>
    <App />
  </HashRouter>
), holder)

This is a topic where RR documentation should add more clarity... To answer your question, you can either use a BrowserRouter , or you can use a Router and pass it a history instance.

Go with the first approach when all your route changes are through Link components.

However, when you need to change routes from your store methods, you would need to use the latter approach. You can write a module which creates and exports a history object and then use the same object in your Router component and in the store methods. It's important to use the same object otherwise the Router won't be able to correctly sync the URL changes with your store.

You may try the code below:

import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

Check the doc here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM