最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Uncaught TypeError: Cannot read property 'props' of undefined in reactJS - Stack Overflow

programmeradmin5浏览0评论

I'm trying out an example in reactJS where I'm displaying a list of records and delete them.Refresh the list after each delete. I saw many questions raised by this error heading, but nothing worked with me.

var CommentBox = React.createClass({
        loadCommentsFromServer: function () {
            $.ajax({
                url: this.props.listUrl,
                dataType: 'json',
                success: function (data) {
                    this.setState({data: data});
                }.bind(this),
                error: function (xhr, status, err) {
                    console.error(this.props.url, status, err.toString());
                }.bind(this),
                cache: false
            });
        },
        getInitialState: function () {
            return {data: []};
        },
        ponentDidMount: function () {
            this.loadCommentsFromServer();
        },
        onClickingDelete: function() {
            alert('Upper layer on click delete called');
            this.loadCommentsFromServer();
        },
        render: function () {
            return (
                    <div className="mentBox">
                        <h1>Static web page</h1>
                        <CommentList data={this.state.data} onClickingDelete={this.onClickingDelete}  />


                    </div>
            );
        }
    });


    var CommentList = React.createClass({
        render: function() {
            if (this.props.data != '') {
                var mentNodes = this.props.data.content.map(function (ment) {

                    return (
                            <div className="ment" key={ment.id}>
                                <h2 className="mentpageName">
                                    {ment.pageName}
                                </h2>

                                <p> {ment.pageContent} </p>

                                <DeleteButton deleteUrl={'/delete/' + ment.id} onClickingDelete={this.props.onClickingDelete}/>

                            </div>
                    );
                });
            }
            return (
                <div className="mentList">
                    {mentNodes}
                </div>
            );
        }
    });

    var DeleteButton = React.createClass({
        onClickingDelete: function() {
            $.ajax({
                url: this.props.deleteUrl,
                type: 'delete',
                success: function () {
                    alert('Successfully deleted');
                    this.props.onClickingDelete();
                }.bind(this),
                error: function (xhr, status, err) {
                   console.error(this.props.deleteUrl, status, err.toString());
                }.bind(this),
                cache: false
            });

        },
        render: function() {
            return (
                <button name={this.props.deleteUrl} onClick={this.onClickingDelete}>Delete</button>
            );
        }
    });


    ReactDOM.render(<CommentBox listUrl="/list/"/>, 
document.getElementById('content'));

On page load, I'm getting

"Uncaught TypeError: Cannot read property 'props' of undefined"

in the CommentList's line call to DeleteButton. Wondering how "this" can go undefined

I'm trying out an example in reactJS where I'm displaying a list of records and delete them.Refresh the list after each delete. I saw many questions raised by this error heading, but nothing worked with me.

var CommentBox = React.createClass({
        loadCommentsFromServer: function () {
            $.ajax({
                url: this.props.listUrl,
                dataType: 'json',
                success: function (data) {
                    this.setState({data: data});
                }.bind(this),
                error: function (xhr, status, err) {
                    console.error(this.props.url, status, err.toString());
                }.bind(this),
                cache: false
            });
        },
        getInitialState: function () {
            return {data: []};
        },
        ponentDidMount: function () {
            this.loadCommentsFromServer();
        },
        onClickingDelete: function() {
            alert('Upper layer on click delete called');
            this.loadCommentsFromServer();
        },
        render: function () {
            return (
                    <div className="mentBox">
                        <h1>Static web page</h1>
                        <CommentList data={this.state.data} onClickingDelete={this.onClickingDelete}  />


                    </div>
            );
        }
    });


    var CommentList = React.createClass({
        render: function() {
            if (this.props.data != '') {
                var mentNodes = this.props.data.content.map(function (ment) {

                    return (
                            <div className="ment" key={ment.id}>
                                <h2 className="mentpageName">
                                    {ment.pageName}
                                </h2>

                                <p> {ment.pageContent} </p>

                                <DeleteButton deleteUrl={'/delete/' + ment.id} onClickingDelete={this.props.onClickingDelete}/>

                            </div>
                    );
                });
            }
            return (
                <div className="mentList">
                    {mentNodes}
                </div>
            );
        }
    });

    var DeleteButton = React.createClass({
        onClickingDelete: function() {
            $.ajax({
                url: this.props.deleteUrl,
                type: 'delete',
                success: function () {
                    alert('Successfully deleted');
                    this.props.onClickingDelete();
                }.bind(this),
                error: function (xhr, status, err) {
                   console.error(this.props.deleteUrl, status, err.toString());
                }.bind(this),
                cache: false
            });

        },
        render: function() {
            return (
                <button name={this.props.deleteUrl} onClick={this.onClickingDelete}>Delete</button>
            );
        }
    });


    ReactDOM.render(<CommentBox listUrl="/list/"/>, 
document.getElementById('content'));

On page load, I'm getting

"Uncaught TypeError: Cannot read property 'props' of undefined"

in the CommentList's line call to DeleteButton. Wondering how "this" can go undefined

Share Improve this question edited Mar 30, 2018 at 7:11 Hakan Fıstık 19.5k16 gold badges123 silver badges147 bronze badges asked May 7, 2016 at 7:05 User1230321User1230321 1,4755 gold badges23 silver badges40 bronze badges 2
  • probably because you are deleting the element. your whole ponent is removed.. but then you are on the callback saying this.props.something. try creating a pointer to your this to call. – John Ruddell Commented May 7, 2016 at 7:16
  • @John, that was working without "onCommentSubmit={this.handleCommentSubmit}" in ment list ponent. Removed that line to avoid confusion. I'm getting the above error on page load. Sorry for that. Please help. – User1230321 Commented May 7, 2016 at 9:34
Add a ment  | 

1 Answer 1

Reset to default 7

When you use array.map, this is undefined and undergoes the normal resolution for this in javascript. In strict mode, it'll stay undefined.

  • Non-strict mode: this resolves to Window

    > [1].map(function(test) {console.log(this)});
    > [object Window]
    
  • Strict mode: this resolves to undefined

    > 'use strict'; [1].map(function(test) {console.log(this)});
    > undefined
    



There are different ways to bind it to the current object.

  • Using map.thisArg

    this.props.data.content.map(function(ment) { ... }, this);
    
  • Using bind

    this.props.data.content.map(function(ment) { ... }).bind(this);
    
  • Using an arrow function

    this.props.data.content.map(ment => { ... });
    
  • Using a variable

    var that = this;
    this.props.data.content.map(function(ment) 
        { ... onClickingDelete={that.props.onClickingDelete} ... });
    


Sources:

If a thisArg parameter is provided to map, it will be passed to callback when invoked, for use as its this value. Otherwise, the value undefined will be passed for use as its this value. https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

In strict mode, the value of this remains at whatever it's set to when entering the execution context. If it's not defined, it remains undefined. https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Operators/this

发布评论

评论列表(0)

  1. 暂无评论