为什么我不能在 React Router 中使用路由器?

Why can't I use routers in React Router?

我对如何使用 react-router v4 有点困惑。我上次使用它时使用的是 v2,它并没有太大不同。我尝试按照一些教程进行操作,但无法正常工作。

我收到这两个错误:

app.bundle.js:358 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

app.bundle.js:304 Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
    at invariant (app.bundle.js:304)
    at ReactCompositeComponentWrapper.instantiateReactComponent [as _instantiateReactComponent] (app.bundle.js:17635)
    at ReactCompositeComponentWrapper.performInitialMount (app.bundle.js:32634)
    at ReactCompositeComponentWrapper.mountComponent (app.bundle.js:32525)
    at Object.mountComponent (app.bundle.js:4197)
    at ReactCompositeComponentWrapper.performInitialMount (app.bundle.js:32638)
    at ReactCompositeComponentWrapper.mountComponent (app.bundle.js:32525)
    at Object.mountComponent (app.bundle.js:4197)
    at mountComponentIntoNode (app.bundle.js:18399)
    at ReactReconcileTransaction.perform (app.bundle.js:6742)

我的应用现在看起来像这样:

import {BrowseRouter, Route, Switch, HashRouter} from 'react-router'

import MyComponent from './components/MyComponent';
    ReactDOM.render(
        <Provider {... stores}>
        <HashRouter>
            <MyComponent />
        </HashRouter>
    </Provider>, document.getElementById('root'));

我尝试了 BrowserRouterHashRouter,但在这两种情况下都会出现相同的问题。我正在使用 MobX,这可能是导致问题的原因。如果我删除我的组件加载的路由内容。我如何让这个路由器的东西工作?

问题是 BrowserRouterHashRouter 都是软件包 react-router-dom 的一部分——不是核心 react-router(v4 中的更改)因此导入它们from react-router 将使它们成为未定义的,因此当您尝试从未定义的元素创建元素时会出现错误。

v4 的一个巨大变化是将 React Router 的不同绑定分成单独的包进行组织,react-router-dom 用于 DOM 绑定,react-router-native 用于 React Native 绑定等, react-router 只持有核心。 BrowserRouterHashRouterDOM 绑定 ,因此存在于 react-router-dom 包中。

SwitchRoute 也来自 react-router-dom 所以从 react-router-dom:

导入它们
import { BrowserRouter, Route, Switch, HashRouter } from "react-router-dom";