2016-09-18 185 views
0

我必须做出反应组件调用网站来进行状态阵营HandleDelete类型错误未定义

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组件与功能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> 
    ); 
    } 
} 

我的目标是删除网站从一个服务器使用ajax里面的WebsiteItem组件(成功完成),并运行一个功能onDelete里面的网站组件更新状态this.state.websites

我不能设法运行该函数的错误:Uncaught TypeError: this.props.onDelete is not a function - 我试图玩bind(this),但不知道如果我完全理解它。谢谢。

回答

1

你几乎说得对。

您必须bind您传递给您的组件实例的回调函数this.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}/> 
     ) 
    }) 
}