如何解决"未捕获的TypeError:未能构建'注释':关于React JS,请使用'new'operarat ....."?

sof*_*fs1 5 html javascript html5 reactjs react-native

我有一个home.jsp在体内

<body>
    <script type="text/babel" src="../resources/scripts/example.js"></script>
     <a href="javascript:Comment();">News</a>
</body>
Run Code Online (Sandbox Code Playgroud)

在另一个example.js中,我有以下内容

alert("I am coming here ... BEEP");

var Comment = React.createClass({
      loadCommentsFromServer: function() {
        $.ajax({
          url: this.props.url,
          dataType: 'json',
          cache: false,
          success: function(data) {
            this.setState({data: data});
          }.bind(this),
          error: function(xhr, status, err) {
            console.error(this.props.url, status, err.toString());
          }.bind(this)
        });
      },
      getInitialState: function() {
        return {data: []};
      },
      componentDidMount: function() {
        this.loadCommentsFromServer();
        setInterval(this.loadCommentsFromServer, this.props.pollInterval);
      },
      render: function() {
        return (
          <div className="comment">       
            <Comment data={this.state.data} />
            <span dangerouslySetInnerHTML={{__html: data}} />
          </div>
        );      
      }
    });

    ReactDOM.render(
      <Comment url="/workingUrl" pollInterval={2000} />,
      document.getElementById('content')
    );
Run Code Online (Sandbox Code Playgroud)

我在Chrome控制台中收到以下错误消息.

Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' 
operator, this DOM object constructor cannot be called as a function.
Run Code Online (Sandbox Code Playgroud)

我在home.jsp文件中添加了React js标签.

如何解决这个问题?请帮我.

Tro*_*son 11

也许这会帮助那些和我有同样问题的人...我只是忘了导入我试图渲染的组件(Webpack/Babel/ES6开发环境):

import { Comment } from './comment'
Run Code Online (Sandbox Code Playgroud)

  • 是的它确实有帮助!有趣的是,eslint没有找到丢失的导入. (2认同)

Nai*_*han 10

你无法做出响应的组件<Comment/>通过Comment().该错误要求您创建Comment类的实例,即这样的事情var comment = new Comment().但是,在你的问题中,我们不需要这个.

<body>
  <a href="javascript:RenderComment();">News</a>
  <div id="content"> </div>
</body>
Run Code Online (Sandbox Code Playgroud)

您的React组件<Comment/>应该是独立的,并将用作参数ReactDOM.render(...).因此,内部Comment不应该有ReactDOM.render(...)功能.此外,锚元素单击不能调用,Comment()因为它不是一个执行渲染的函数,而是一个安装在Classinstance上的函数DOM.在单击<a/>标记时,RenderComment()应调用a ,然后再渲染<Comment/>组件.

var RenderComment = function RenderComment() {
  ReactDOM.render(React.createElement(
                    "div", null, " ", Comment, " "
                  ), document.getElementById("content"));
};
Run Code Online (Sandbox Code Playgroud)

在这里,我们将渲染您使用的<Comment/>组件React.createClass.

var Comment = React.createClass({
 // Your component functions and render() method
 // No ReactDOM.render() method here
}
Run Code Online (Sandbox Code Playgroud)