简体   繁体   English

使用react-router 4.0.0的路由器历史记录

[英]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 react-router 4.0.0 ,历史记录似乎已经改变,使用以下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. 我浏览了代码,但找不到任何示例或API如何更改。

React Router v4 changed things little bit. React Router v4改变了一点点。 They made separate top level router elements. 他们制作了单独的顶级路由器元素。 Replace <Router history={hashHistory}> with <HashRouter> in your code. 在代码中用<HashRouter>替换<Router history={hashHistory}>

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 . hashHistory不再是react-router的导出对象。 If you want to use a hash history, you can just render a <HashRouter> . 如果要使用哈希历史记录,则只需呈现<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. 这是RR文档应该增加更多清晰度的主题...要回答您的问题,您可以使用BrowserRouter ,也可以使用路由器并将其传递给历史记录实例。

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. 使用相同的对象非常重要,否则路由器将无法正确地将URL更改与您的商店同步。

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. 在这里查看文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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