反应通过ID未定义删除

时间:2019-04-22 18:10:49

标签: javascript node.js reactjs fetch

我正在尝试使用React通过ID删除项目。我的后端路由正常工作(节点和postgresql)。每次我尝试删除项目时,它都会在页面刷新时恢复。我的命令行说我要删除的项目未定义。

如果我输入一个特定的ID(URL + ID),它可以工作,但不能动态运行。这是一个物品的例子 0:{item_id:1,item_name:“ Kivik沙发”,item_price:799,item_brand:“ IKEA”,item_category:“ furniture”,...}

   export default class MainContainer extends Component {
  state = {
        items: []
    }
     addItem = (item) => {
        let newItem = this.state.items
        newItem.push(item)
        this.setState({
            items: newItem
        })
    }
//Delete Item
    deleteItem = (item) => {
        let newItem = this.state.items
        newItem.splice(item, 1);
        this.setState({
            items: newItem
        })
    }

   getItems = async () => {

    try {
      const items = await fetch('http://localhost:9000/items/');
      const itemsJson = await items.json();
      this.setState({items: itemsJson});
      return itemsJson
    } catch (err) {
      console.log(err, 'error in catch block')
      return err
  }

}


   //delete
    handleDelete = (event,)=>{


    event.preventDefault();
        fetch('http://localhost:9000/items/' + this.state.items.item_id, {
            method: 'DELETE',
            headers: { 
              'Accept': 'application/json',
              'Content-Type': 'application/json' },
                body: JSON.stringify({
                "item_id": this.state.items.item_id,

            })
              })

    this.deleteItem(event.currentTarget.value)

  }

 componentDidMount(){
    this.getItems().then((data) => console.log(data,'my items'));
  } 



render(){
const itemsList = this.state.items.map((items, index)=>{
return <li className="card" key={index}><Link to={{pathname:`/item/${items.item_id}`, state:items}}>{items.item_id}. {items.item_brand} {items.item_name} ${items.item_price}</Link> <button className="tiny button" value={index} onClick={this.handleDelete}><Icon name="trash" /></button></li>
  })
    return (
         <div className="App">
         <h1>Items</h1>
         <ol className="Grid">{itemsList}</ol>
         <Forms addItem ={this.addItem} />
         </div>
      )
  }
}

我希望该项目在前端和后端永久删除,但是要删除的项目是不确定的,并且在刷新后,该项目返回前端。

1 个答案:

答案 0 :(得分:0)

将句柄删除更改如下。

handleDelete = (event) => {
  // gets the index of the clicked item from value={index}
  const index = event.target.value;
  const item = this.state.items[index];

  event.preventDefault(); 

  if (!item || !item.item_id) {
    alert("No item!");
    return;
  }

  fetch("http://localhost:9000/items/" + item.item_id, {
    method: "DELETE",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      item_id: item.item_id
    })
  });

  this.deleteItem(event.currentTarget.value);
};