【问题标题】:React - Uncaught Invariant Violation:React - 未捕获的不变违规:
【发布时间】:2016-06-17 16:58:10
【问题描述】:

当我在浏览器上运行我的代码时,我收到了这个错误消息。

未捕获的不变违规:MyComponent.render():有效的 React 必须返回元素(或 null)。您可能返回了未定义的, 数组或其他一些无效对象。

我使用 Atom 作为我的代码编辑器并在 chrome Web 服务器上运行。这是我的代码。

<body>
<div id="react-comp"></div>
  <script type="text/babel">
    var MyComponent = React.createClass({
      render: function() {
        return
          <div>
            <h1>{this.props.text}</h1>

          </div>;
      }
    });

    ReactDOM.render(
      <div>
        <MyComponent text="Hello World"/>
        <MyComponent text="Hello"/>
      </div>  
    , document.getElementById('react-comp'));


  </script>
</body>

可能是 jsx 转换问题?或任何其他的东西?

【问题讨论】:

  • 您可以使用非缩小版查看完整的错误信息。
  • @Jack 现在我可以看到完整的错误消息了。说明已更新。

标签: javascript reactjs


【解决方案1】:

您可能会在 return 之后遇到 JavaScript 的自动分号插入。只需删除 div 之前的换行符即可。

var MyComponent = React.createClass({
  render: function() {
    return <div> // Change this line
        <h1>{this.props.text}</h1>

      </div>;
  }
});

【讨论】:

  • 现在工作正常!感谢您的详细回答:)
【解决方案2】:

我不知道你使用的是哪个版本的 React,因为我知道如果 JSX 语法没有用 () 包裹,一些旧版本会出错。 尝试在 MyComponent 的 render 方法上这样做:

render: function() {
    return (
      <div>
        <h1>{this.props.text}</h1>
      </div>
    );
  }

【讨论】:

    【解决方案3】:

    只需将渲染函数更改为

    var MyComponent = React.createClass({
      render: function() {
        return (
          <div>
            <h1>{this.props.text}</h1>    
          </div>
        );
      }
    });
    

    Daniel 的建议也是正确的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2017-02-09
      • 2015-07-07
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多