我目前正在尝试使用react router v4将我的导航栏与ReactDOM.render()函数分开。但是如何使用新的反应路由器v4和链接组件将导航栏移动到单独的文件?
我的应用程序的起点client.js
:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter as Router, Route, Link} from 'react-router-dom';
import store from './store';
import NavBar from './components/NavBar.react';
import WelcomePage from './components/Pages/Welcome.react';
import LoginPage from './components/Pages/Login.react';
const app = document.getElementById('app');
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<NavBar />
<Route exact path="/" component={WelcomePage} />
<Route path="/login" component={LoginPage} />
</div>
</Router>
</Provider>, app);
我的分隔导航栏文件NavBar.react.js
:
import React from "react";
import { connect } from "react-redux";
import { Link } from 'react-router';
export default class NavBar extends React.Component {
render() {
return (
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
<hr/>
</div>
)
}
}
运行此代码会引发以下错误:
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. Check the render method of `NavBar`.
at invariant (invariant.js:44)
at instantiateReactComponent (instantiateReactComponent.js:74)
at instantiateChild (ReactChildReconciler.js:44)
at ReactChildReconciler.js:71
at traverseAllChildrenImpl (traverseAllChildren.js:77)
at traverseAllChildren (traverseAllChildren.js:172)
at Object.instantiateChildren (ReactChildReconciler.js:70)
at ReactDOMComponent._reconcilerInstantiateChildren (ReactMultiChild.js:187)
at ReactDOMComponent.mountChildren (ReactMultiChild.js:226)
at ReactDOMComponent._createInitialChildren (ReactDOMComponent.js:697)
如果我删除行<NavBar />
或将我的NavBar的JSX内容移动到client.js
文件,它就有效......
到目前为止,我刚刚在互联网上找到了一些人们将导航栏集成到ReactDOM.render()函数中的例子。
答案 0 :(得分:1)
您正在从&#39;路由器&#39;中导入链接。在您的Navbar组件中。如果您已安装&#34; react-router&#34;这将有效。和&#34; react-router-dom&#34;,而你可能想做的只是import { Link } from 'react-router-dom';
因为看起来你已经安装了react-router-dom
。