React中的确认窗口

22

我有以下的代码:

renderPosts() {
return _.map(this.state.catalogue, (catalogue, key) => {
  return (
    <div className="item col-md-3" key={key} id={key}>
        <img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
        <h3>{catalogue.marque}</h3>
        <h4>{catalogue.numero}</h4>
        <h4>{catalogue.reference}</h4>
        <p>{catalogue.cote}</p>
        <div className="text-center">
        <button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection.bind(this, key)};}}>Supprimer</button>
        </div>

    </div>
  )
 })
}

我也有这个函数:

removeToCollection(key, e) {

  const item = key;
  firebase.database().ref(`catalogue/${item}`).remove();
 }
当我在“onclick”按钮中不使用确认窗口的功能时,代码能够正常运行。但是当我想要使用确认窗口时,确认窗口会显示出来,但我的项目并没有被删除。
有什么想法吗?
谢谢您的帮助!
3个回答

33
基本上你是在绑定函数而不是调用它……你应该事先绑定,最好在构造函数中……然后调用它。
尝试这样做: ```js functionName.bind(this); functionName(); ```

注意:以上代码仅为示例,并非通用解决方案。

renderPosts() {
  this.removeToCollection = this.removeToCollection.bind(this);
  return _.map(this.state.catalogue, (catalogue, key) => {
    return (
      <div className="item col-md-3" key={key} id={key}>
          <img src={this.state.catalogue[key].avatarURL} height={150} with={150}/>
          <h3>{catalogue.marque}</h3>
          <h4>{catalogue.numero}</h4>
          <h4>{catalogue.reference}</h4>
          <p>{catalogue.cote}</p>
          <div className="text-center">
          <button className="btn btn-danger" onClick={() => {if(window.confirm('Delete the item?')){this.removeToCollection(key, e)};}}>Supprimer</button>
          </div>

      </div>
    )
  })
}


我希望代码片段中没有语法错误,以便能够看到结果。 - Narges Pms

13

您只是绑定了函数但没有调用它。

正确的语法是使用bind并调用已绑定的函数。

if (window.confirm("Delete the item?")) {
    let removeToCollection = this.removeToCollection.bind(this, 11);//bind will return to reference to binded function and not call it.
    removeToCollection();
}

您也可以这样做,而无需绑定事件。

if (window.confirm("Delete the item?")) {
  this.removeToCollection(11);
}

如果this是在removeToCollection内部引起的问题,则使用箭头函数来定义它。

removeToCollection=(key)=> {
    console.log(key);
  }

使用codesandbox演示进行工作。


7

我做的与下面相同:

我有一个智能(类)组件

<Link to={`#`} onClick={() => {if(window.confirm('Are you sure to delete this record?')){ this.deleteHandler(item.id)};}}> <i className="material-icons">Delete</i> </Link>

我定义了一个函数来调用删除端点,代码如下:

deleteHandler(props){
    axios.delete(`http://localhost:3000/api/v1/product?id=${props}`)
    .then(res => {
      console.log('Deleted Successfully.');
    })
  }

对我来说这很有效!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接