【问题标题】:React Router and HistoryReact 路由器和历史
【发布时间】:2017-06-11 14:18:38
【问题描述】:

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

您提供了一个使用历史 v4.x 或 v2.x 及更早版本创建的历史对象。这个版本的 React Router 只兼容 v3 历史对象。请更改为历史 v3.x。在不变量这是我的代码:

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

任何建议将不胜感激!谢谢!

【问题讨论】:

标签: javascript reactjs ecmascript-6 react-router


【解决方案1】:

您错误地使用了历史记录和组件。您不需要在历史记录和组件对象周围加上引号

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

【讨论】:

  • 有时很难找出解决方案,特别是当错误没有引导您走向正确的道路时。希望能解决你的问题
【解决方案2】:

来自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'))

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2021-11-01
    • 1970-01-01
    • 2017-08-03
    • 2020-06-14
    • 2022-07-25
    • 2020-02-13
    • 2017-08-19
    • 1970-01-01
    相关资源
    最近更新 更多