运行我的应用程序时,出现此错误两次。
元素类型无效:应使用字符串(对于内置组件)或类/函数(对于复合组件),但得到:未定义
{
"name": "react-poc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "npm run build",
"build": "webpack -d && cp src/index.html dist/index.html && webpack-dev-server --content-base src/ --inline --hot",
"build:prod": "webpack -p && cp src/index.html dist/index.html"
},
"keywords": [
"reactjs"
],
"author": "Ankur",
"license": "MIT",
"dependencies": {
"react": "^16.4.1",
"react-dom": "^16.4.1",
"react-router": "^4.3.1"
},
"devDependencies": {
"babel-core": "^6.26.3",
"babel-loader": "^7.1.4",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-stage-2": "^6.24.1",
"webpack": "^4.12.0",
"webpack-cli": "^3.0.8",
"webpack-dev-server": "^3.1.4"
}
}
var path = require('path'),
DIST_DIR = path.resolve(__dirname,"dist"),
SRC_DIR = path.resolve(__dirname,"src");
var config ={
entry: SRC_DIR + "/app/index.js",
output: {
path:DIST_DIR + "/app",
filename:"bundle.js",
publicPath: "/app/"
},
module: {
rules:[
{
test: /.jsx?$/,
loader: "babel-loader",
exclude:/node_modules/,
include:SRC_DIR,
query:
{
presets:["react","es2015","stage-2"]
}
}
]
}
};
module.exports = config;
import React, { Component } from "react";
import { render } from "react-dom";
import { BrowserRouter, Route } from "react-router";
import {User} from "./components/User";
import {Root} from "./components/Root";
class App extends React.Component {
render() {
return (
<BrowserRouter>
<div>
<Route path="/" component={Root} />
<Route path="/user" component={User} />
</div>
</BrowserRouter>
);
}
}
render(<App />, document.getElementById("root"));
import React from "react";
import {Header} from "./Header"
export class Root extends React.Component {
render() {
return (
<div className="container">
<div className="row">
<div className="col-10">
<Header />
</div>
</div>
<div className="row">
<div className="col-10">
</div>
</div>
</div>
);
}
}
import React from 'react'
export class User extends React.Component{
render(){
return(
<div>
<h3>
User Page
</h3>
<p>User ID:</p>
</div>
);
}
}
import React from "react";
export const Header = (props) => {
return (
<nav className="navbar navbar-default">
<div className="container">
<div className="navbar-header">
<ul className="nav navbar-nav">
<li><a href="#">Home</a></li>
<li><a href="#">User</a></li>
</ul>
</div>
</div>
</nav>
);
};
Webpack编译时不显示任何错误,仅当应用程序运行时,我才在控制台中看到错误。堆栈溢出中也有类似的问题,试图遵循那里的建议对我没有用。
答案 0 :(得分:1)
您使用的是命名出口,因此导入应该
import {User} from "./components/User";
import {Root} from "./components/Root";
或将导出更改为默认值
class User extends React.Component{ ...}
export default User;
UPD
您也不需要react-router-dom
来获得BrowserRouter
import { BrowserRouter, Route } from "react-router-dom"; // not react-router
答案 1 :(得分:1)