How to resolve "Uncaught TypeError: failed to create comment": use the "new" operator ..... "in relation to React JS?

I have home.jsp where inside the body

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

In a separate .js example, I have the following

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')
    );

The following error appears in the Chrome console.

Uncaught TypeError: Failed to construct 'Comment': Please use the 'new' 
operator, this DOM object constructor cannot be called as a function.

I have added React js tags to the home.jsp file.

How to fix it? Please help me.

+4
source share
2 answers

You cannot invoke React Component <Comment/>on Comment(). The error requires creating an instance of the Commentie class , something like this var comment = new Comment(). However, we don’t need this in your problem.

<body>
  <a href="javascript:RenderComment();">News</a>
  <div id="content"> </div>
</body>

React Component <Comment/> ReactDOM.render(...). , Comment ReactDOM.render(...). , Comment(), , , Class, instance DOM. <a/> RenderComment(), , , <Comment/>.

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

<Comment/>, React.createClass.

var Comment = React.createClass({
 // Your component functions and render() method
 // No ReactDOM.render() method here
}
+7

, -, , ... , ( Webpack/Babel/ES6):

import { Comment } from './comment'
+3

Source: https://habr.com/ru/post/1620491/


All Articles