繁体   English   中英

如何从输入字段获取ID并在ReactJS和Axios中通过该ID删除

[英]How to get ID from a input field and DELETE by that ID in ReactJS and Axios

我想从Axios用DELETE请求删除特定对象:

这是我的代码,用于填充并获取对象信息:

const rowEvents = {
  onClick: (e, row, rowIndex) => {
    this.setState({
      carId: this.state.cars[rowIndex].carId,
      brand: this.state.cars[rowIndex].brand,
      model: this.state.cars[rowIndex].model,
      color: this.state.cars[rowIndex].color,
      topSpeed: this.state.cars[rowIndex].topSpeed
    });
  }
};

当我单击该行时,将在输入字段中获取数据:

这是我的删除功能

handleDelete = carId => {
  axios
    .delete("https://localhost:44369/api/car/DeleteCar/", {
      params: { id: carId }
    })
    .then(response => {
      console.log(response);
    });
};

为了从字段中获取ID,我有一个输入隐藏字段,如下所示:

<input type="hidden" id="carId" value={this.state.carId} />;

填写完字段后,我想根据ID删除该对象,然后单击该行:

 <button type="submit" className="btn btn-danger mr-1" onClick={this.handleDelete(document.getElementById("carId"))}> Delete record</button>

我在控制台中收到以下错误:

TypeError:将圆形结构转换为JSON

我试图像这样传递参数{this.state.carId}

仍然没有成功

我尝试过的解决方案:

如何在React中使用axios删除单个项目

如何在React中访问DOM元素? 什么是React中document.getElementById()的等效项

如何使用ReactJS获取输入字段的值?

如何根据输入字段中的ID删除对象?

您不必将carId作为参数传递,因为您将其保存为状态。

您可以访问carId通过调用this.state.carId

handleDelete = () => {
  axios
    .delete("https://localhost:44369/api/car/DeleteCar/", {
      params: { id: this.state.carId }
    })
    .then(response => {
      console.log(response);
    });
};

您可以尝试做console.log(document.getElementById("carId"))吗? 我怀疑您正在获取整个元素,而不仅仅是获得您为其分配的值。 我认为将其更改为onClick={this.handleDelete(document.getElementById("carId").value)}可以解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM