错误:元素类型无效:期望一个字符串(对于内置组件) - reactjs

时间:2018-01-19 16:17:49

标签: javascript reactjs

我收到此错误消息:

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, or you might have mixed up default and named imports.

main.js:

var React       = require('react');
var ReactDOM    = require('react-dom');
var createReactClass = require('create-react-class');

import {BrowserRouter} from 'react-router';
var Route = BrowserRouter.Route;

import App from 'App';

const routes = (
<BrowserRouter>

    <Route path="/" component={App} />

</BrowserRouter>
);

ReactDOM.render(routes, document.getElementById('app'));

App.js:

var React       = require('react');
var ReactDOM    = require('react-dom');
var createReactClass = require('create-react-class');


export default class App extends React.Component {



    render()
    {
        return (
            <div>       
                <h2>masoud</h2>
            </div>
        );
    }


}

我更改了这一行:

import {BrowserRouter} from 'react-router';

import BrowserRouter from 'react-router';

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

但它没有奏效,我也遇到了同样的错误。

3 个答案:

答案 0 :(得分:1)

可能因为你的App导入,试试这个,

import App from './App';

我认为 App.js main.js 位于同一根目录

答案 1 :(得分:1)

写作时

import App from 'App';

它查找App组件在名为App的node_modules包中,这不是您的意图,您需要在导入时指定path/to/App

import App from 'path/to/App';

此外,BrowserRouter是从react-router-dom包导出而不是react-router,您需要先安装

npm install -S react-router-dom

然后写

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

检查 documentation

答案 2 :(得分:0)

尝试更改import {BrowserRouter} from 'react-router';

import BrowserRouter from 'react-router';

还要确保使用正确的react-router软件包。根据您使用的版本,您必须import BrowserRouter from 'react-router-dom'