如何使用 React 和 Node 从服务器和 UI 中删除数据?

How to delete data from server and UI using React and Node?

I want to delete data from UI and Server, I write this code, but the problem is when I click the Delete button data was deleted from UI but still exists in the server. After reloading the page deleted data showed in the UI again. when I console.log(data) the result is { acknowledged: true, deletedCount: 0 }.

/* server side code */

app.delete('/data/:id', async (req, res) => {
        const id = req.params.id
        const query = { _id: ObjectId(id) }
        const result = await dataCollection.deleteOne(query)
        res.send(result)
    })



/* client side code */

const [data, setData] = useData()

 const deleteData = async (id) => {

        const confirmation = window.confirm('Are you sure about delete the data ?')

        if (confirmation) {
            const { data } = await axios.delete(`http://localhost:5000/data/${id}`, product)
            const exist = data.filter( x => x._id !== id);
            setData(exist)
        })

    }

The result { acknowledged: true, deletedCount: 0 }
Expected result { acknowledged: true, deletedCount: 1 }

您的其他代码存在一些问题,您使用了自定义挂钩 useData 。您的服务器响应表明数据已从服务器中删除,请尝试再次从服务器获取数据并使用新数据更新 ui 内容。我将在下面留下一个工作版本演示:

function SingleProductMng({ item, products, setProducts }) { // here props are drilled in parent container
// here item is the single item to render
// products and setProducts is custom useState hook to render data from server
const { _id, name, supplier, price, quantity, category } = item;

const handleDelete = () => {
    if (window.confirm('Are you sure you want to delete?')) {
        console.log('deleted');
        fetch(`your server url`, {
            method: 'DELETE',
            headers: {
                'content-type': 'application/json',
            },
            body: JSON.stringify(item),
        });

        const filteredItem = products.filter((product) => product._id !== _id);
        setProducts(filteredItem);
    } else {
        console.log('cancel');
    }
};
        return (<>components</>)