React HandleDelete TypeError undefined

时间:2016-09-18 10:07:19

标签: javascript reactjs react-rails

我有一个名为Websites的React组件来处理状态

class Websites extends React.Component {

  constructor(props) {
    super(props);
    this.handleWebsiteDelete = this.handleWebsiteDelete.bind(this);
    this.state = {
      websites: this.props.websites
    }
  }

  handleWebsiteDelete(id) {
    console.log("delete")
    // How to Run This Function?
    // ...further code to delete id from state.websites
  }

  render () {
    return(
      <div className="row">
        {
          this.state.websites.map(function(website, index) {
            return (
              <WebsiteItem key={website.id} {...website} onDelete={this.handleWebsiteDelete}/>
            )
          })
        }
      </div>
    );
  }
}

然后我有一个名为WebsiteItem的React组件,其函数handleDelete是一个对象:

class WebsiteItem extends React.Component {

  handleDelete(e) {
    e.preventDefault();
    $.ajax({
      method: "DELETE",
      url: "/websites/" + this.props.id 
    })
      .done(function(){
        this.props.onDelete(this.props.id);
      }.bind(this))
  }

  render() {
    return (
      <div className="card">
        {this.props.name}
        <a href="#" onClick={this.handleDelete.bind(this)}>Delete</a>
      </div>
    );
  }
}

我的目标是使用WebsiteItem组件内的ajax从服务器中删除网站(已成功完成)并在网站组件中运行函数onDelete以更新状态this.state.websites

我无法通过错误运行该函数:Uncaught TypeError: this.props.onDelete is not a function - 我尝试使用bind(this)但不确定我是否完全理解它。谢谢。

1 个答案:

答案 0 :(得分:1)

你几乎做对了。

您必须bindthis.state.websites.map()传递给组件实例的回调函数。

为了做到这一点,你必须将上下文作为第二个参数传递给.map()

{
    this.state.websites.map(function(website, index) {
        return (
          <WebsiteItem key={website.id} {...website} onDelete={this.handleWebsiteDelete}/>
        )
    },this)
}

或使用箭头功能

{
    this.state.websites.map((website, index) => {
        return (
          <WebsiteItem key={website.id} {...website} onDelete={this.handleWebsiteDelete}/>
        )
    })
}