反应路由器和历史

时间:2017-01-26 06:24:21

标签: javascript reactjs ecmascript-6 react-router

你好,我真的很反应,我正在从Learncode.academy观看这个精彩的youtube ReactJs教程。本教程是从去年开始的,我不知道这些模块是否已被弃用。我收到了以下错误消息:

  

您提供了使用history v4.x或v2.x及更早版本创建的历史记录对象。此版本的React Router仅与v3历史对象兼容。请更改为历史v3.x. at invariant这是我的代码:

    import Layout from "./components/Layout";
    import { Router, Route, IndexRoute, browserHistory } from "react-router";

    const app = document.getElementById('app');

    ReactDOM.render(
      <Router history="{browserHistory}">
       <Route path="/" component="{Layout}">
       </Route>
      </Router>,
    app);

这是我的package.json

"history": "^3.2.1",
"react-router": "^3.0.2",

任何建议都将受到高度赞赏!谢谢!

2 个答案:

答案 0 :(得分:4)

您正在错误地使用历史记录和组件。您不需要围绕历史记录和组件对象的引号

import Layout from "./components/Layout";
import { Router, Route, IndexRoute, browserHistory } from "react-router";

const app = document.getElementById('app');

ReactDOM.render(
  <Router history={browserHistory}>
   <Route path="/" component={Layout}>
   </Route>
  </Router>,
app);

答案 1 :(得分:0)

来自https://github.com/ReactTraining/react-router/issues/353

使basename适用于react-router@3.0.2:

npm install --save react-router@3.0.2

npm install --save history@^3.0.0

(检查react-router package.json以获取正确的历史版本,历史的当前主要版本是4.x,不能与react-router@3.0.2一起使用)

import React from 'react'
import { render } from 'react-dom'
import { Router, Route, IndexRoute, useRouterHistory } from 'react-router'
import { createHistory } from 'history'

const history = useRouterHistory(createHistory)({
  basename: '/subdirectory-where-the-app-is-hosted-goes-here'
})

render((
  <Router history={history}>
    <Route path='/' component={Layout}>
      <IndexRoute component={HomeView} />
      <Route path='other-views' component={OtherViews} />
    </Route>
  </Router>
), document.getElementById('main'))