【问题标题】:How to use delete request with axios in react project and Firebase?如何在反应项目和 Firebase 中使用带有 axios 的删除请求?
【发布时间】:2021-04-23 17:09:13
【问题描述】:

我需要删除元素但不知道如何获取该特定元素! 这是 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 中删除所选元素。看来我的网址是错误的,因为它删除了所有元素。

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database axios


    【解决方案1】:

    既然你来电:

    axios.delete("/goals.json")
    

    Firebase 确实会那个节点,这意味着它会删除你的所有目标。

    如果要删除特定节点,则需要指定该特定节点的路径:

    axios.delete("/goals/-MRMLoUzCCLA2A3xRWeb.json")
    

    因此,您需要将点击目标的键从 HTML 传递给 deleteGoalHandler,然后将其传递给数据库目标。幸运的是,您已经将它存储在每个目标的 id 属性中,所以它在 J​​SX/HTML 中应该是这样的:

    clicked={deleteGoalHandler(goal.id)}
    

    【讨论】:

    • 它不会只删除第一个元素,因为我需要删除选择的元素吗?
    • 我的回答中的 delete 调用是返回 JSON 中的第一个节点的示例。我的示例中的 JSX 传入 goal.id,然后您需要将其在 URL 中传递给 REST API。
    • 嘿@Max。你在这方面有什么进展吗?
    猜你喜欢
    • 2019-03-12
    • 2018-12-06
    • 2018-08-31
    • 2018-04-10
    • 2018-04-09
    • 2019-02-02
    • 2021-12-26
    • 2020-03-08
    • 2018-12-24
    相关资源
    最近更新 更多