【问题标题】:How to get ID from a input field and DELETE by that ID in ReactJS and Axios如何从输入字段中获取 ID 并在 ReactJS 和 Axios 中通过该 ID 删除
【发布时间】:2019-07-01 12:10:33
【问题描述】:

我想通过 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}这样传递参数

还是没有成功

我尝试过的解决方案:

how to delete a single item using axios in react

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

How to get the value of an input field using ReactJS?

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

【问题讨论】:

    标签: javascript html reactjs react-native http


    【解决方案1】:

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

    您可以拨打this.state.carId访问carId

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

    【讨论】:

    • 如果OP有行数,每行都有删除按钮怎么办?
    • 如果它在地图内,您可以像 data.map(item => { })
    • 很好,这正在工作!非常感谢您的宝贵时间
    • 从问题中可以看出carId是存储在一个状态变量中
    • 在这种情况下,您的代码会失败,最好编辑您的答案。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 1970-01-01
      • 2020-11-28
      • 2015-05-15
      • 2019-04-19
      相关资源
      最近更新 更多