製品を削除しようとしていますが、成功したと表示されません。削除する製品の ID を取得する方法がわかりません
私のボタン onClick = {handleDelete} は、他のフォルダーのコンポーネントからインポートされています。 handleDelete 関数を作成しようとしましたが、この場合は何かが不足しています。
これはそのセクションのコードです
import React, { useState, useEffect } from "react";
import { Container, Row, Col, Table } from "react-bootstrap";
import Loading from "../../components/Loading";
import Button from "../../components/Button/index"
import firebaseApp from "../../api/config";
const ProductTableList = ({
products,
loading,
fetchProductRequest
}) => {
useEffect(() => {
fetchProductRequest();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const firebaseDb = firebaseApp.database();
const [currentId, setCurrentId] = useState("");
if (loading) {
return (
<Container>
<Row>
<Col>
<Loading />
</Col>
</Row>
</Container>
);
}
const handleDelete = (id) => {
const productId = firebaseDb.ref().push().key;
if (window.confirm("Are you sure to delete this record?")) {
firebaseDb
.ref("products")
.child(`products/${productId}`)
.remove((err) => {
if (err) console.log(err);
else setCurrentId("");
});
}
}
const handleUpdate = (event) => {
//TODO
}
return (
<Table striped bordered hover className="product-table">
<thead>
<tr>
<th>No.</th>
<th className="image">Image</th>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
{!!products && products.length > 0 ? (
products.map((product, index) => {
return (
<tr key={index}>
<td>{index}</td>
<td>{product.image}</td>
<td>{product.name}</td>
<td>{product.category}</td>
<td>{product.price}</td>
<td>{product.description}</td>
<td>
<Button onClick={handleDelete} btnText="Delete" />
<Button onClick={handleUpdate} btnText="Update" />
</td>
</tr>
);
})
) :
(
<tr><td className="center-title">Product list is empty!</td></tr>
)}
</tbody>
</Table>
)
}
export default ProductTableList;
誰か助けてくれませんか?選択した製品を削除するにはどうすればよいですか
誰かがその理由を説明またはサポートしてもらえますか?本当にありがとうございました
------------------------
フックが正しく機能するには、毎回同じ順序で呼び出されることが必要です。それらはコンディションとは言えませんついに。
ただし、コンポーネントでは、loading が true の場合、関数から早期に戻るため、一部のレンダリングで currentId useState が呼び出されなくなります。これは、許可されていない useState フックを条件付きで呼び出していることを意味します。
これを修正するには、状態呼び出しを if (loading) { ステートメントの上に移動します。