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

时间:2017-07-01 05:47:43

标签: reactjs react-router react-router-v4 mobx-react

我对如何使用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,这可能是造成问题的原因。如果我删除了我的组件加载的路由选项。如何让这个路由器工作?

1 个答案:

答案 0 :(得分:1)

问题是BrowserRouterHashRouter都是包react-router-dom的一部分 - 而不是核心react-router(v4中的更改),因此从react-router导入它们当您尝试从undefined创建元素时,{1}}将使它们未定义,从而导致错误。

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

SwitchRoute也来自react-router-dom,因此请从react-router-dom导入:

import { BrowserRouter, Route, Switch, HashRouter } from "react-router-dom";