[英]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中訪問DOM元素? 什么是React中document.getElementById()的等效項
如何根據輸入字段中的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.