快速路由器删除

时间:2018-03-08 12:30:21

标签: reactjs api express mern

我使用MERN堆栈(Mongo,Express,React,Node)编写了一个简单的“Grocery List”Web应用程序。我遇到的问题是除非我重新加载页面,否则我的DELETE REST命令不会被触发。下面是我的事件处理程序和后端的源代码。

事件处理程序

handleRemove(e) {
        fetch('http://localhost:3001/list/' + e._id, {
            headers: {
                "Access-Control-Allow-Credentials": true,
                "Access-Control-Allow-Origin": "*",
                "Content-Type": "application/json"
            },
            method: "DELETE",
            body: e
        })
        this.refs.list.forceUpdate();
    }

快速后端

router.delete('/list' +'/:id',function(req,res) {
        item.remove({
            _id: req.params.id
        }, function(err) {
            if(err) {
                res.header("Access-Control-Allow-Headers", "Authorization, Origin, X-Requested-With, Content-Type, Accept");
                res.header("Access-Control-Allow-Methods", "PATCH, POST, GET, PUT, DELETE, OPTIONS");
                res.header("Access-Control-Allow-Methods", "POST, GET, DELETE");
                res.header("Access-Control-Allow-Credentials", "true");
                return res.send(err);
            } else {
                console.log("successfully deleted")
            }
        })
    })

的OnClick

<button onClick={() =>
          this.props.handleRemove(item)}
          className="item" key={item._id + "btn"}>Remove</button>

链接到我的回购 https://github.com/ahahn95/GroceryList

2 个答案:

答案 0 :(得分:0)

确保正确调用handleRemove onClick。

如果它在页面加载时变得坚固,那么我怀疑你是这样做的:

<button onClick={this.handleRemove()}>Delete</button>

当你应该这样做时:

<button onClick={() => this.handleRemove()}>Delete</button>

答案 1 :(得分:0)

DELETE命令正在启动。这不会更新UI。

您必须更新state

handleRemove

handleRemove(e) {
  fetch('http://localhost:3001/list/' + e._id, {
    headers: {
      "Access-Control-Allow-Credentials": true,
      "Access-Control-Allow-Origin": "*",
      "Content-Type": "application/json"
    },
    method: "DELETE",
    body: e
  })
  .then(res => res.json())
  .then(json => {
    this.setState({items: this.state.items.filter(item => { 
      return item._id !== e._id // change this to match your code if necessary
    })});
    // this.refs.list.forceUpdate(); not sure what this does
  })
  .catch(err => console.log(err));
}