reactjs中未定义的函数

Undefined function in reactjs

本文关键字:函数 未定义 reactjs      更新时间:2023-09-26

不知道我在这里做错了什么,但基本是:

/** @jsx React.DOM */
/**
 * Deal with creating a set of posts for a table.
 */
var PostRow = React.createClass({
  handleDelete: function(id){
    var postToDelete = AisisWriter.Models.Post();
    postToDelete.set({id: this});
    posttoDelete.destroy().then(this.deleted, this.fail)
    return false;
  },
  deleted: function() {
    console.log('Success - check the db for this post');
  },
  fail: function() {
    console.log('Fail');
  },
  render: function(){
    // Loop through the post objects.
    var post = this.props.posts.map(function(postObject) {
        var content = null;
        var title = null;
        // Cut off the text at anything over 140 characters
        if (postObject.content.length > 140){
           content = postObject.content.substr(0, 140) + '...';
        }else{
          content = postObject.content;
        }
        // Cut off the text at anything voer 20 characters
        if (postObject.title.length > 20){
          title = postObject.title.substr(0, 20) + '...';
        }else{
          title = postObject.title;
        }
        // Return the rows of the table.
        // React makes us have a unique key.
        return (
          <tr key={postObject.id}>
            <td>{title}</td>
            <td>{content}</td>
            <td>
              <a href={"#/post/" + postObject.id} className="btn btn-primary move-right-10px">View</a>
              <a href={"#/post/" + postObject.id + '/edit'} className="btn btn-success move-right-10px">Edit</a>
              <button className="btn btn-danger" onClick={this.handleDelete(postObject.id)}>Delete</button>
            </td>
          </tr>
        );
    });
    // Finially return the rows (note the div)
    return (
          <div>{post}</div>
      );
  }
});

我得到的问题是,如果我这样做:this.handleDelete生活是伟大的,页面将加载。但是我需要传递这个特定的post id的id,所以我试着做你看到的:this.handleDelete(postObject.id)在那一点上我得到:Uncaught TypeError: undefined is not a function在整个this.handleDelete(postOject.id)

我进入call back hell了吗?我做错了什么吗?

当使用Array.prototype.map时,函数的上下文默认落在全局作用域,即this在浏览器中指向window。您可以在调用map时传递上下文,将其设置为代码所期望的组件:

// Add a `this` as the second argument to `map` to set the context to
// the current component. `this.handleDelete` will then refer to the component's
// `handleDelete` function like you are expecting.
var post = this.props.posts.map(function(postObject) {
  ...
    <button className="btn btn-danger" onClick={this.handleDelete.bind(this, postObject.id)}>Delete</button>
  ...
}, this);

您还需要绑定回调函数以传递postObject.id

// The current form is a function call
this.handleDelete(postObject.id)
// `bind` returns a new function that will be passed `postObject.id` when it is
// called by React.
this.handleDelete.bind(this, postObject.id)