【发布时间】:2021-07-02 01:42:46
【问题描述】:
大家好,我的按钮删除有问题,我尝试按 id 删除值,我使用函数 .find 来检索 Id,我的获取请求和发布请求运行良好,我使用邮递员测试我的删除路线以及它的工作。我尝试了一些选项但没有成功,现在我被阻止了。 抱歉,如果我的帖子不清楚它是我在 stackoverflow 上的第一次
import axios from 'axios';
import React, { useEffect, useState } from 'react';
const Hazard = () => {
const [hazardName, setHazardName] = useState('');
const [hazardList, setHazardList] = useState([]);
const handleChangeHazard = (event) => {
setHazardName(event.target.value);
};
useEffect(() => {
const urlHazard = 'http://localhost:8000/hazards';
axios.get(urlHazard).then((response) => {
setHazardList(response.data);
});
}, []);
const handleAddHazard = (event) => {
event.preventDefault();
const postUrl = 'http://localhost:8000/hazards/add';
axios
.post(
postUrl,
{
hazardName,
},
{
headers: {
'Content-Type': 'application/json',
},
}
)
.then((response) => {
console.log(response.data);
window.location.reload();
})
.catch((error) => console.error(error));
};
const deleteHazard = (id) => {
const urlDelete = `http://localhost:8000/hazards/${id}`;
const removeId = hazardList.find((list) => list._id !== hazardList._id);
console.log(removeId);
axios
.delete(urlDelete)
.then((response) => {
setHazardList(removeId).then(response.data);
})
.catch((error) => console.error(error));
};
return (
<div className="input-select">
<h3 className="hazard-title">Aléas</h3>
<form className="form-hazard">
<div className="form-hazard-input">
<select
onChange={handleChangeHazard}
name="Aléas"
className="aleas-select"
value={hazardName}
>
{hazardList.map((val) => (
<option key={val._id}>{val.hazardName}</option>
))}
</select>
<input
className="add-hazard"
type="text"
name="text"
value={hazardName}
onChange={handleChangeHazard}
/>
<button
className="post-hazard"
type="submit"
onClick={handleAddHazard}
>
Ajouter
</button>
<button
className="delete-hazard"
type="button"
onClick={deleteHazard}
>
Supprimer
</button>
</div>
</form>
</div>
);
};
export default Hazard;
【问题讨论】:
-
在deleteharzad函数中,你没有使用removeId,id是事件。你不能把它作为axios的参数。
-
id 是一个事件是什么意思?我需要定位价值吗?并在我的按钮上放一个 onChange ?在 RemoveId 的 console.log 上,我有一个像这样的对象 {_id: "605b57bfaebad11a0475e426", hazardName: "Bureau", v: 0} hazardName: "Bureau" __v: 0 _id: "605b57bfaebad11a0475e426" __proto 当我检查控制台时,我的浏览器上有一个 id,但是当我用我的选择更改值时,这个永远不会改变它总是相同的