尝试得到react-router (v4.0.0)和react-hot loader (3.0.0-beta.6)很好地发挥,但在浏览器控制台得到以下错误:

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.

index.js:

import React from 'react';
import ReactDom from 'react-dom';
import routes from './routes.js';
require('jquery');
import 'bootstrap/dist/css/bootstrap.min.css';
import 'bootstrap/dist/js/bootstrap.min.js';
import './css/main.css';

const renderApp = (appRoutes) => {
    ReactDom.render(appRoutes, document.getElementById('root'));
};

renderApp( routes() );

routes.js:

import React from 'react';
import { AppContainer } from 'react-hot-loader';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import store from './store/store.js';
import { Provider } from 'react-redux';
import App from './containers/App.jsx';
import Products from './containers/shop/Products.jsx';
import Basket from './containers/shop/Basket.jsx';

const routes = () => (

    <AppContainer>
        <Provider store={store}>
            <Router history={browserHistory}>
                <Route path="/" component={App}>
                    <IndexRoute component={Products} />
                    <Route path="/basket" component={Basket} />
                </Route>
            </Router>
        </Provider>
    </AppContainer>

);

export default routes;

当前回答

大多数情况下,这表示导入/导出错误。但是要注意,不仅要确保堆栈跟踪中引用的文件本身得到了良好的导出,还要确保该文件正确地导入了其他组件。在我的例子中,错误是这样的:

import React from //注意末尾的.css,这是错误的原因! import SeeminglyUnimportantComponent from './SeeminglyUnimportantComponent.css'; Const组件= (props) => ( < div > < SeeminglyUnimportantComponent / > {/ *……这里的组件代码*/} < / div > ); 导出默认组件;

其他回答

我已经遇到过这个问题了。我的解决方案是:

在文件配置路由:

const routes = [
    { path: '/', title: '', component: Home },
    { path: '*', title: '', component: NotFound }
]

to:

const routes = [
    { path: '/', title: '', component: <Home /> },
    { path: '*', title: '', component: <NotFound /> }
]

您需要了解命名导出和默认导出。我什么时候应该用大括号导入ES6 ?

在我的例子中,我通过改变

import Provider from 'react-redux'

to

import { Provider } from 'react-redux'

这真的很简单。当我开始编写React时,我遇到了这个问题,这个问题几乎总是因为导入:

import React, { memo } from 'react';

你可以对它进行解构,因为react lib有一个memo属性,但你不能这样解构

import { user } from 'assets/images/icons/Profile.svg';

因为它不是一个对象。

希望能有所帮助!

循环依赖也是原因之一。(一般)

我所缺少的是我正在使用

import { Router, Route, browserHistory, IndexRoute } from 'react-router';

正确答案应该是:

import { BrowserRouter as Router, Route } from 'react-router-dom';

当然你需要添加npm包react-router-dom:

npm install react-router-dom@next --save