【问题标题】:CRUD firestore React function delete()CRUD firestore React 函数 delete()
【发布时间】:2021-10-27 19:48:20
【问题描述】:

我正在尝试使用 React 和 Firestore 为 CRUD 执行删除功能,我已经设法消除它,问题是我获取 ID 的方式,因为它总是删除表中较低的记录。

函数删除()

const handleDelete = async(id) =>{
/* setData([]); */
   
console.log(id)
try {
  
   /* await db.collection('empleado').doc(id).delete(); */ 
  
} catch (error) {
  console.log(error)
}
  }

获取身份证

useEffect(()=>{
  
db.collection('empleado')
.onSnapshot((querySnapshot) =>{ 
  querySnapshot.forEach(doc =>{
    setData(data => [ ...data,[doc.data().dleted,doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
  });
})

db.collection('empleado').onSnapshot((snapshot)=>{
  setId(snapshot.docs.map((doc) => ({id: doc.id})))
})
   
  },[]);

onClick功能按钮参数

{
name: "Delete",
options: {
  filter: true,
  sort: false,
  empty: true,
  customBodyRender: (value, tableMeta, updateValue) => {
    return (
      <button  onClick={ ()=>handleDelete(id) }>
        Delete
      </button>
    );
  }
}
  },

这是我的 console.log()

(4) [{…}, {…}, {…}, {…}]
0: {id: "48DIVsf7NLc5ux5vfH76"}
1: {id: "B3Jnpmmtipmi3IwvxKzs"}
2: {id: "cSPnc9lDpgvWNDXsXhfo"}
3: {id: "rLzJuLFfanXTSArA9fd2"}
length: 4
[[Prototype]]: Array(0)

当按下按钮删除(任何行按钮删除)时会发生这种情况,我想上传我的表格的图像。

组件

import React,{useEffect} from 'react';
import "../../../css/employee.css";
import Dashboard from '../Dashboard';
import { db } from '../../../firebase';
import MUIDataTable from "mui-datatables";
import Form from 'react-bootstrap/Form';
import Col from 'react-bootstrap/Col';
import Row from 'react-bootstrap/Row';

function Employee(){
  const [data,setData] = React.useState([]);
  const[id,setId]=React.useState('');
  const[dleted,setDleted]=React.useState('');
  
  const handleDelete = async(id) =>{
    /* setData([]); */
    console.log(id)
    try {
       /* await db.collection('empleado').doc(id).delete(); */ 
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(()=>{
      
    db.collection('empleado')
    .onSnapshot((querySnapshot) =>{ 
      querySnapshot.forEach(doc =>{
        setData(data => [ ...data,[doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
      });
    })

    db.collection('empleado').onSnapshot((snapshot)=>{
      setId(snapshot.docs.map((doc) => ({id: doc.id, data:doc.data()})))
    })
   
  },[]);
  const columns =[{
    name: "Delete",
    options: {
      filter: true,
      sort: false,
      empty: true,
      customBodyRender: (value, tableMeta, updateValue) => {
        return (
          <button  onClick={ ()=>handleDelete(id)}> 
        Delete
      </button>
        );
      }
    }
  },
   "TIPO DOCUMENTO", "DOCUMENTO", "LUGAR EXPEDICION", "NOMBRE","DIRECCION","TELEFONO","EMAIL","CARGO","RH","EPS","TIEMPO SUELDO","SUELDO"];

 const options = {
   filterType: 'checkbox',
 };


  return(
    <div id="employ">

    <div><Dashboard /></div>
    
    <hr/>

<div style={{marginLeft:'18em'}}>
<MUIDataTable 
title={"EMPLEADOS"} 
data={data} 
columns={columns} 
options={options} 
/>

</div>

 


    </div>
  );
}
export default Employee;

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore crud delete-row


    【解决方案1】:

    试试这个:

    <button  onClick={ ()=>handleDelete(tableMeta.rowData[0])}> //you have to put the index of your id here
            Delete
          </button>
    

    【讨论】:

    • 不起作用,我认为问题出在获取 ID 时,我不知道如何仅获取行的当前 ID,请查看更新帖子。
    【解决方案2】:

    解决方案

    组件员工

    import React,{useEffect} from 'react';
    import "../../../css/employee.css";
    import Dashboard from '../Dashboard';
    import { db } from '../../../firebase';
    
    import MUIDataTable from "mui-datatables";
    
    import Form from 'react-bootstrap/Form';
    import Col from 'react-bootstrap/Col';
    import Row from 'react-bootstrap/Row';
    
    function Employee(){
    
    
    
      const [data,setData] = React.useState([]);
    
      const[id,setId]=React.useState('');
      const[dleted,setDleted]=React.useState('');
    
       const [tipoDoc, setTipoDoc] = React.useState('');
      const [doc, setDoc] = React.useState('');
      const [lugarExp, setLugarExp] = React.useState('');
      const [nombre, setNombre] = React.useState('');
      const [direccion, setDireccion] = React.useState('');
      const [telefono, setTelefono] = React.useState('');
      const [email, setEmail] = React.useState('');
      const [cargo, setCargo] = React.useState('');
      const [rh, setRh] = React.useState('');
      const [eps, setEps] = React.useState('');
      const [tiempoPago, setTiempoPago] = React.useState('');
      const [sueldo, setSueldo] = React.useState('');
    
    
    
    
    
      const handleSubmit = async (e) => {
        
        e?.preventDefault();
        setData([]);
        
        db.collection("empleado").add({
          tipoDoc: tipoDoc,
          doc: doc,
          lugarExp: lugarExp,
          nombre: nombre,
          direccion: direccion,
          telefono: telefono,
          email: email,
          cargo: cargo,
          rh:rh,
          eps:eps,
          tiempoPago:tiempoPago,
          sueldo:sueldo,
          
        }).then(() => {
          
        }).catch((error) => {
          alert(error.message)
        });
      }
     
      const handleDelete = async(id,index) =>{
         setData([]); 
        let parse = '';
        let parse2='';
        console.log(id);
        console.log(index);
        parse = parseInt(index);
        
         for (let i = 0; i < id.length; i++) {
          if(i === parse ){
            const element = id[i];
            console.log("element",typeof(element))
            parse2 = element;
            console.log("B3Jnpmmtipmi3IwvxKzs"==parse2)
              await db.collection("empleado").doc(parse2).delete().then(() => {
              console.log("Document successfully deleted!");
          }).catch((error) => {
              console.error("Error removing document: ", error);
          });  
          }
         
        }
           
      }
    
      useEffect(()=>{
          
        db.collection('empleado')
        .onSnapshot((querySnapshot) =>{ 
          querySnapshot.forEach(doc =>{
            setData(data => [ ...data,[doc.data().tipoDoc,doc.data().doc,doc.data().lugarExp,doc.data().nombre,doc.data().direccion, doc.data().telefono,doc.data().email,doc.data().cargo,doc.data().rh,doc.data().eps,doc.data().tiempoPago,doc.data().sueldo]]);
          });
        })
    
        db.collection('empleado').onSnapshot((snapshot)=>{
          setId(snapshot.docs.map((doc) => (doc.id)))
        })
       
      },[]);
    
    
    
      const columns =[{
        name: "Delete",
        options: {
          filter: true,
          sort: false,
          empty: true,
          customBodyRender: (value, tableMeta, updateValue) => {
            return (
              <button  onClick={ ()=>handleDelete(id,`${tableMeta.rowIndex}`)}> 
            Delete
          </button>
            );
          }
        }
      },
      , "TIPO DOCUMENTO", "DOCUMENTO", "LUGAR EXPEDICION", "NOMBRE","DIRECCION","TELEFONO","EMAIL","CARGO","RH","EPS","TIEMPO SUELDO","SUELDO"];
    
     const options = {
       filterType: 'checkbox',
     };
    
    
      return(
        <div id="employ">
    
        <div><Dashboard /></div>
        
        <hr/>
    
    <div style={{marginLeft:'18em'}}>
    <MUIDataTable 
    title={"EMPLEADOS"} 
    data={data} 
    columns={columns} 
    options={options} 
    />
    
    </div>
    
     <hr />
        <hr /><br /><br /><br/>
        <Form id="form-contact">
          <Row className="mb-3">
    
          <Form.Group as={Col} controlId="formGridState">
              <Form.Label>Tipo documento</Form.Label>
              <Form.Select defaultValue="-" value={tipoDoc} onChange={e => { setTipoDoc(e.target.value) }}>
                <option>-</option>
                <option>Tarjeta Identidad</option>
                <option>Cedula Ciudadania</option>
                <option>Cedula Extranjeria</option>
              </Form.Select>
            </Form.Group>
    
            <Form.Group as={Col} controlId="formGridEmail">
              <Form.Label>Documento</Form.Label>
              <Form.Control type="text" value={doc} onChange={e => { setDoc(e.target.value) }} placeholder="0000000" />
            </Form.Group>
    
            <Form.Group as={Col} controlId="formGridPassword">
              <Form.Label>Lugar expedicion</Form.Label>
              <Form.Control type="text" value={lugarExp} onChange={e => { setLugarExp(e.target.value) }} placeholder="municipio/departamento" />
            </Form.Group>
          </Row>
    
          <Form.Group className="mb-3" controlId="formGridAddress1">
            <Form.Label>Nombre</Form.Label>
            <Form.Control type="text" placeholder="name" value={nombre} onChange={e => { setNombre(e.target.value) }} />
          </Form.Group>
    
          <Form.Group className="mb-3" controlId="formGridAddress2">
            <Form.Label>Direccion</Form.Label>
            <Form.Control placeholder="Cra - #" value={direccion} onChange={e => { setDireccion(e.target.value) }} />
          </Form.Group>
    
          <Row className="mb-3">
            <Form.Group as={Col} controlId="formGridCity">
              <Form.Label>Telefono </Form.Label>
              <Form.Control value={telefono} onChange={e => { setTelefono(e.target.value) }} />
            </Form.Group>
    
            <Form.Group as={Col} controlId="formGridCity">
              <Form.Label>Email </Form.Label>
              <Form.Control value={email} onChange={e => { setEmail(e.target.value) }} />
            </Form.Group>
    
            <Form.Group as={Col} controlId="formGridCity">
              <Form.Label>Cargo </Form.Label>
              <Form.Control value={cargo} onChange={e => { setCargo(e.target.value) }} />
            </Form.Group>
            
    
            <Form.Group as={Col} controlId="formGridState">
              <Form.Label>RH</Form.Label>
              <Form.Select defaultValue="-" value={rh} onChange={e => { setRh(e.target.value) }}>
                <option>-</option>
                <option>A+</option>
                <option>AB+</option>
                <option>O+</option>
              </Form.Select>
            </Form.Group>
    
            <Form.Group as={Col} controlId="formGridCity">
              <Form.Label>EPS </Form.Label>
              <Form.Control value={eps} onChange={e => { setEps(e.target.value) }} />
            </Form.Group>
    
            <Form.Group as={Col} controlId="formGridCity">
              <Form.Label>Tiempo pago </Form.Label>
              <Form.Control value={tiempoPago} onChange={e => { setTiempoPago(e.target.value) }} />
            </Form.Group>
            <Form.Group as={Col} controlId="formGridCity">
              <Form.Label>Sueldo </Form.Label>
              <Form.Control value={sueldo} onChange={e => { setSueldo(e.target.value) }} />
            </Form.Group>
          </Row>
    
          <Form.Group className="mb-3" id="formGridCheckbox" style={{textAlign:'left'}}>
            <Form.Check type="checkbox" label="Acepto términos del servicio y tratamiento de datos." />
          </Form.Group>
    
          <button type="button" class="btn btn-secondary btn-lg"  onClick={()=>handleSubmit()} >Agregar</button>
          
       
        </Form>
    <hr/>
    <hr/> 
    
    
        </div>
      );
    }
    export default Employee;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-16
      • 2021-11-05
      • 2020-06-26
      • 2020-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多