如何使用 ReactJS 删除 table 中的一行,同时捕获已删除对象的 ID 并将其发送到服务器

How to Delete a row in a table using ReactJS, while capturing the ID of the deleted object and send it to server

我对 ReactJS 的了解有限,我想知道如何删除选定的行,然后将 id 保存在变量中以将其发送到服务器,最好使用 Axios。

还有就是不在 URL 中发送 Id?

函数Table() {

useEffect(() => {
    Axios.get("http://localhost:3001/api/get/carmodels").then((response) => {
      setCarModelList(response.data)
    })
  }, [])

  const [carModelList, setCarModelList] = useState([])

  const DeleteCar = (val) => { //assigning val the id of the object
    
   const deleteCarModel = Axios.delete(`http://localhost:3001/api/delete/${val}`); //sending it to backend

    return deleteCarModel

  }

  

  const renderTableData = () => {
    return carModelList.map((val) => (
        <tr class>
           <td>{val.id}</td>
            <td>{val.brand}</td>
            <td>{val.model}</td>
            <td>{val.price}</td>
            <td>
                <button>Delete</button> //how do I insert DeleteCar() here?
            </td>
        </tr>))
  }

return (
    <table id="table">
    <thead>
        <tr>
          <th>Id</th>
          <th>Brand</th>
          <th>Model</th>
          <th>Price</th>
        </tr>
      </thead>
      <tbody>
          {renderTableData()}
      </tbody>
      </table>
    );
  

}

导出默认值Table

非常感谢!

通过状态更新改进 DeleteCar 功能,这样您无需重新加载视图就可以看到更改

const DeleteCar = (val) => {
 // create a new array object
 const next = [...carModelList];
 // remove and save the item of interest to your variable
 const removedItems = next.splice(next.indexOf(val), 1);
 // your axios function formatted for /delete/:id
 const deleteCarModel = Axios.delete(`http://localhost:3001/api/delete/${val.id}`);
 // update react state with the new array
 setCarModelList(next);
}

并回答您评论中的问题:

<button onPress={() => DeleteCar(val)}>Delete</button>