我对如何使用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'));
我尝试了BrowserRouter
和HashRouter
,但两种情况都出现了同样的问题。我正在使用MobX,这可能是造成问题的原因。如果我删除了我的组件加载的路由选项。如何让这个路由器工作?
答案 0 :(得分:1)
问题是BrowserRouter
和HashRouter
都是包react-router-dom
的一部分 - 而不是核心react-router
(v4中的更改),因此从react-router
导入它们当您尝试从undefined创建元素时,{1}}将使它们未定义,从而导致错误。
v4的一个巨大变化是将React Router的不同绑定分离为单独的组织包,react-router-dom
用于DOM绑定,react-router-native
用于React Native绑定等,用react-router
只持有核心。 BrowserRouter
和HashRouter
是 DOM绑定,因此存在于react-router-dom
包中。
Switch
和Route
也来自react-router-dom
,因此请从react-router-dom
导入:
import { BrowserRouter, Route, Switch, HashRouter } from "react-router-dom";