未捕获的错误:缩小的 React 错误 #130

IT技术 javascript node.js reactjs react-native webpack
2021-05-21 01:03:25

所以这是我的代码的样子

---------index.js-----

var React =require('react');
var ReactDOM =require('react-dom');
var App=require('../components/App');

ReactDOM.render(<App />, document.getElementById('app'));

---------App.js-----

var React = require('react');

class App extends React.Component {
    render() {
        return(
            <div>
                <h1>HI wassup</h1>
            </div>
        );
    }
}
export default App;

---------package.json-----

{
    "name": "views",
    "version": "1.0.0",
    "description": "learning",
    "main": "index.js",
    "scripts": {
        "start": "webpack-dev-server --mode development --hot && webpack"
    },
    "author": "vinayak",
    "license": "ISC",
    "dependencies": {
        "react": "^16.4.2",
        "react-dom": "^16.4.2"
    },
    "devDependencies": {
        "babel-core": "^6.26.3",
        "babel-loader": "^7.1.5",
        "babel-preset-react": "^6.24.1",
        "html-webpack-plugin": "^3.2.0",
        "unminified-webpack-plugin": "^2.0.0",
        "webpack": "^4.16.5",
        "webpack-cli": "^3.1.0",
        "webpack-dev-server": "^3.1.5"
    }
}

---------webpackconfig----

const HTMLWebpackPlugin=require('html-webpack-plugin');
const webpack=require('webpack');
const UnminifiedWebpackPlugin = require('unminified-webpack-plugin');
const HTMLWebpackPluginConfig=new HTMLWebpackPlugin({
    template: '../../views/index.hbs',
    filename:'index.hbs'
});

module.exports={
    entry:__dirname + '/app/index.js',
    module:{
        rules:[
        {
            test:/\.js$/,
            exclude:/node_modules/,
            loader:'babel-loader'
        }
        ]
    },
    plugins: [
        new UnminifiedWebpackPlugin(),
        new webpack.DefinePlugin({
            'process.env': {
                NODE_ENV: JSON.stringify('development')
            }
        })
    ],
    devtool: 'source-map',
    output:{
        filename:'app.js',
        path:__dirname + '../../public/javascripts/'
    },
    devServer:{
        inline:false
    }

};

----------文件夹结构-------------

|react
    |node modules
    |components
        |App.js
|app
    |index.js

一切正常,但是当我在浏览器中执行应用程序时,我收到react错误并提供一个显示以下内容的链接。

“元素类型无效:应为字符串(对于内置组件)或类/函数(对于复合组件),但得到:对象。”

2个回答

你混淆了require, 和import/ export

由于您正在运行 webpack,因此您的所有 React 代码(以及通过 webpack 由 babel 转译的任何内容)都应该坚持使用导入/导出。require应该只在像 js 这样直接由 node.js 运行的地方使用。

在您的 index.js 中,更改导入的所有要求,看看是否有帮助。

在文件中index.js,您应该像这样更改代码:

var App = require('../components/App').default;

或使用 import

import App from '../components/App';

我推荐使用统一用法。你可以import/exportmodule.exports/require