【问题标题】:React + Webpack: React.createElement: type should not be null, undefined, boolean, or numberReact + Webpack:React.createElement:类型不应为 null、undefined、boolean 或 number
【发布时间】:2017-02-21 21:16:37
【问题描述】:

为什么我在 chrome 的控制台中收到该错误?

我的代码:

index.html

<!DOCTYPE html>
<html>
<head>
<title>hello React</title>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="root">
<!-- my app renders here -->
</div>

    <script src="../react-15.3.1/build/react.js"></script>
    <script src="../react-15.3.1/build/react-dom.js"></script>
    <script src="./dist/bundle.js"></script>
</body>
</html>

main.js

import SalutaMondo from './salutamondo';

var UnaProva = React.createClass({

   render: function(){
      return (
         <div>
            <SalutaMondo/>
            <div>Ciao Emiliano</div>
         </div>
      );
   },

});

ReactDOM.render(<UnaProva />, document.getElementById("root"));

salutamondo.js

    var SalutaMondo = React.createClass({
       render: function(){
          return (
             <h1>Hello World</h1>
          );

       }


    });

module.export = SalutaMondo;

webpack.config.js

const webpack = require('webpack')
const path = require('path')

module.exports = {
  entry: [ './src/salutamondo.js', './src/main.js' ],
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.js?$/,
        exclude: /node_modules/,        
        loader: 'babel-loader',
        query: {
          presets: ['react', 'es2015']
        }
      }
    ]
  }
}

【问题讨论】:

  • 为什么有两个入口点?为什么你在一个地方使用module.exports 而在另一个地方使用import?你不应该只使用export var SalutaMondo = ...吗?

标签: reactjs


【解决方案1】:

在您的 webpack 配置中,您使用的是 babel-loader。这意味着您正在使用 ES6 样式的模块。在salutamondo.js 中,您使用的是 CommonJS 样式的模块。结果,babel-loader 没有选择模块。你可以试试:

export default SalutaMondo;

代替:

module.export = SalutaMondo;

【讨论】:

  • 那么我应该扩展 React.Component 而不是也使用 React.createClass 吗?
  • 你可以做任何一个,这取决于你喜欢什么样的风格,我通常使用 React.createClass 因为它不会从 babel 中拉出额外的膨胀。来自文档:“如果你还没有使用 ES6,你可以使用 React.createClass 帮助器。” facebook.github.io/react/docs/react-component.html
  • @xRobot 此页面包含更多关于使用 React 和不使用 ES6 的区别的信息:facebook.github.io/react/docs/react-without-es6.html
【解决方案2】:

这可能是由于salutamondo.js 使用 CommonJS 模块格式,而main.js 使用 ECMAScript 模块。我建议将所有内容都保存在 ECMAScript 模块中:

    var SalutaMondo = React.createClass({
       render: function(){
          return (
             <h1>Hello World</h1>
          );

       }


    });

export default SalutaMondo;

【讨论】:

  • 那么我应该扩展 React.Component 而不是也使用 React.createClass 吗?
  • @xRobot 是的,最好。 createClass 将是 deprecated in React 15.5
猜你喜欢
  • 1970-01-01
  • 2023-01-22
  • 2022-10-22
  • 2023-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
相关资源
最近更新 更多