![](/img/trans.png)
[英]How to use a custom React hook to make a POST or DELETE request with Axios
[英]How to use delete request with axios in react project and Firebase?
我需要刪除該元素,但不知道如何獲取該特定元素! 這是Firebase上的數據結構
這是代碼:
import React, {useState, useEffect} from 'react';
import classes from "./Goal.css";
import Button from "../UI/Button/Button";
import axios from '../../axios-goals'
const Goal = () => {
const [goal, setGoal] = useState({
goals: [],
error: false
});
const deleteGoalHandler = (event) => {
event.preventDefault();
axios.delete("/goals.json")
.then(response => {
console.log(response.data);
})
.catch(error => error => {
setGoal({error: true})
})
}
useEffect(() => {
axios.get('/goals.json')
.then(response => {
const fetchedGoals = [];
for (let key in response.data) {
fetchedGoals.push({
...response.data[key],
id: key
})
}
setGoal({goals: fetchedGoals, error: false})
})
.catch(error => {
setGoal({error: true})
})
}, [])
return (
<div className={classes.MyGoals}>
{goal.goals.map(goal => (
<div key={goal.goalData.goalName} className={classes.Goal}>
<h3>{goal.goalData.goalName}</h3>
<p style={{fontSize: '13px', color: '#cbcbcb'}}>{goal.goalData.commentToGoal}</p>
<div className={classes.GoalDetails}>
<p>{goal.goalData.importance}</p>
<p>{goal.goalData.timer}</p>
</div>
<form>
<Button btnType="Success">DONE</Button>
<Button btnType="Danger" clicked={deleteGoalHandler}>CANCEL</Button>
</form>
</div>
))}
</div>
);
};
export default Goal;
當你按下取消按鈕時,選擇的元素必須從Firebase中刪除。看來我的url是錯誤的,因為它刪除了所有元素。
既然你打電話:
axios.delete("/goals.json")
Firebase 確實是該節點,這意味着它會刪除您的所有目標。
如果您希望它刪除特定節點,則需要指定該特定節點的路徑:
axios.delete("/goals/-MRMLoUzCCLA2A3xRWeb.json")
因此,您需要將點擊目標的鍵從 HTML 傳遞給deleteGoalHandler
,然后將其傳遞給數據庫目標。 幸運的是,您已經將它存儲在每個目標的id
屬性中,所以它在 JSX/HTML 中應該是這樣的:
clicked={deleteGoalHandler(goal.id)}
當然,您要刪除整個文檔。 它一定要是:
axios.delete(/goals/${ /goals/${id}.json
);
其中 id 變量已從您的目標變量傳遞
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.