【问题标题】:reactjs with react-router doesn't workreactjs 与 react-router 不起作用
【发布时间】:2017-09-03 11:06:03
【问题描述】:

我正在尝试获得一个运行 nodejs 的简单 reactjs SPA,但我的路由器无法正常工作。 我使用 create-react-app 创建了一个新应用程序并添加了 npm install react-router。 我的 package.json 是

{
"name": "App",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^15.5.0",
"react-dom": "^15.5.0",
"react-router": "^4.0.0"
    },
"devDependencies": {
    "react-scripts": "0.9.5"
},
"scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
}
}

我只是将 react 组件放在与 src/compoents/ 不同的文件夹中 我的 index.js 是

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

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

这在方面起作用。该应用程序出现并显示来自 reactjs 的 hello world 示例。 但是当我用路由器替换应用程序时

<Router history={ hashHistory }>
    <Route path='/' component={ App }/>
</Router>

应用程序中断。即使使用 IndexRoute,该应用程序也无法运行。

将 hasHistory 更改为 browserHistory 或 createMemoryHistory 不会改变任何内容。

您能否给我一个正确方向的提示,我缺少什么?

【问题讨论】:

  • 应用程序是如何崩溃的?您遇到了什么错误?
  • 在控制台中我收到一条警告说需要历史记录类型错误:this.props.history is undefined 警告:失败的道具类型:道具historyRouter 中被标记为必需,但是它的值为undefined。在路由器中(在 index.js:8 处)
  • 您正在以4.0之前版本的方式初始化react-router,请检查the docs for setting up react-router 4.0或降级到旧版本的包
  • 能否请您简短回答一下,我可以奖励您?

标签: javascript node.js reactjs react-router


【解决方案1】:

@Rob M. 你是我的英雄! 谢谢! 这正是重点。

当我将 react-router 的版本更改为 2.8 时。正如你所建议的,它工作得很好。

如果我正确理解文档,建议使用 react-router-dom 代替更高级别的路由器

<BrowserRouter>
<HashRouter>
<MemoryRouter>
<NativeRouter>
<StaticRouter>

我理解对了吗?

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 2018-07-31
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 2020-05-19
    • 2014-04-16
    • 2021-04-06
    相关资源
    最近更新 更多