axios 在try {}块内将state设置为true,但在组件重新呈现时state会自动切换回false

46scxncf  于 2022-11-23  发布在  iOS
关注(0)|答案(2)|浏览(84)

我正在尝试在成功的axios.delete调用后实现一个成功确认弹出模态。
删除可以正常工作,甚至console.log()也可以在我的条件渲染中工作,但我注意到我的初始状态是false,在成功删除时(在try块中),状态变为true,但一旦组件重新渲染,状态又变回false,导致我的弹出模态无法渲染。
我不确定是try块的问题还是我试图呈现弹出模态的方式的问题。
初始状态

const [showSuccess, setShowSuccess] = useState(false);

axios请求

const deleteService = async (id: number) => {
     try {
       const JWT = await getCookie("auth");
       const { data } = await axios(
       `/api/serviceType/${id}`, {
       method: "DELETE",
       headers: {
         "Content-Type": "application/json",
         Authorization: JWT,
       },
       });

       setData(data);

      // Success Alert Popup
      setShowSuccess(true);
   
     } catch (e) {
      
       // Error Alert Popup
       setShowAlert(true);
     }
  };

catch块内部的警报状态更改按需工作!
条件渲染

// Table state update on submit
  useEffect(() => {
    fetchData(data);
  }, [data]);

  // Success Alert
  if (showSuccess === true) {
    return (
      <>
        <Modal show={show} onHide={() => {setShowSuccess(false); handleClose(); }} backdrop="static">
        <Modal.Header closeButton style={{ backgroundColor: "#00E676"}}></Modal.Header>
        <AlertDialog 
          title={"Success!"} 
          message={"Service Type was successfully deleted."}
        />  
      </Modal>
      </>
    )
  }

if (showAlert === true) {
    return (
      <>
      <Modal show={show} onHide={() => {setShowAlert(false); handleClose(); }} backdrop="static">
        <Modal.Header closeButton style={{ backgroundColor: "#FF1744"}}></Modal.Header>
        <AlertDialog 
          title={"Error Deleting Data"} 
          message={"There was an error deleting the Service."}
        />  
      </Modal>
      </> 
    )
  } 

  return (
    <>
      <Trash onClick={handleShow}/>

      <Modal show={show} backdrop="static" onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Delete Service</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Are you sure you want to delete this Service? This process cannot be undone.
        </Modal.Body>
        <Modal.Footer>
          <Button variant="outline-dark" onClick={handleClose}>
            Cancel
          </Button>
          <Button type="submit" variant="danger" onClick={() => deleteService(id)}>
            Delete
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );

错误模态和确认模态有效,成功模态无效。
整个组件

import React, { useState, useEffect } from 'react';
import { getCookie } from "../../../utils/cookies";
import axios from "axios";
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import { Trash } from 'react-bootstrap-icons';
import AlertDialog from '../../../alerts/AlertDialog';

export default function DeleteService({ fetchData, id }) {
  const [show, setShow] = useState(false);

  const handleClose = () => setShow(false);
  const handleShow = () => setShow(true);

  const [isLoading, setIsLoading] = useState(true);
  const [data, setData] = useState([]);

  // Success Dialog
  const [showSuccess, setShowSuccess] = useState(false);
  console.log(showSuccess)

  // Error Dialog
  const [showAlert, setShowAlert] = useState(false);

  // DELETE
  const deleteService = async (id: number) => {
     try {
       const JWT = await getCookie("auth");
       const { data } = await axios(
       `/api/serviceType/${id}`, {
       method: "DELETE",
       headers: {
         "Content-Type": "application/json",
         Authorization: JWT,
       },
       });

       setData(data);
       setIsLoading(false);

       // Hides Modal on submission
       setShow(false);

      // Success Alert Popup
      setShowSuccess(true);
   
     } catch (e) {
       setIsLoading(false);
       
       // Error Alert Popup
       setShowAlert(true);
     }
  };

  // Table state update on submit
  useEffect(() => {
    fetchData(data);
  }, [data]);

  // Success Alert
  if (showSuccess === true) {
    return (
      <>
        <Modal show={show} onHide={() => {setShowSuccess(false); handleClose(); }} backdrop="static">
        <Modal.Header closeButton style={{ backgroundColor: "#00E676"}}></Modal.Header>
        <AlertDialog 
          title={"Success!"} 
          message={"Service was successfully deleted."}
        />  
      </Modal>
      </>
    )
  }

  if (showAlert === true) {
    return (
      <>
      <Modal show={show} onHide={() => {setShowAlert(false); handleClose(); }} backdrop="static">
        <Modal.Header closeButton style={{ backgroundColor: "#FF1744"}}></Modal.Header>
        <AlertDialog 
          title={"Error Deleting Data"} 
          message={"There was an error deleting the Service."}
        />  
      </Modal>
      </> 
    )
  } 

  return (
    <>
      <Trash onClick={handleShow}/>

      <Modal show={show} backdrop="static" onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Delete Service</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Are you sure you want to delete this Service? This process cannot be undone.
        </Modal.Body>
        <Modal.Footer>
          <Button variant="outline-dark" onClick={handleClose}>
            Cancel
          </Button>
          <Button type="submit" variant="danger" onClick={() => deleteService(id)}>
            Delete
          </Button>
        </Modal.Footer>
      </Modal>
    </>
  );
}
qni6mghb

qni6mghb1#

在将showSuccess设置为true之前,将show设置为false。请记住,所有的模态都依赖于show
您已经有了单独的变量来显示其他模态,那么为什么不使用它们呢?
show更改为showDelete(为清楚起见),并将返回更改为:

return (
    <>
      <Trash onClick={handleShow}/>

      <Modal show={showDelete} backdrop="static" onHide={handleClose}>
        <Modal.Header closeButton>
          <Modal.Title>Delete Service</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          Are you sure you want to delete this Service? This process cannot be undone.
        </Modal.Body>
        <Modal.Footer>
          <Button variant="outline-dark" onClick={handleClose}>
            Cancel
          </Button>
          <Button type="submit" variant="danger" onClick={() => deleteService(id)}>
            Delete
          </Button>
        </Modal.Footer>
      </Modal>

      <Modal show={showSuccess} onHide={() => {setShowSuccess(false); handleClose(); }} backdrop="static">
        <Modal.Header closeButton style={{ backgroundColor: "#00E676"}}></Modal.Header>
        <AlertDialog 
          title={"Success!"} 
          message={"Service was successfully deleted."}
        />  
      </Modal>

      <Modal show={showAlert} onHide={() => {setShowAlert(false); handleClose(); }} backdrop="static">
        <Modal.Header closeButton style={{ backgroundColor: "#FF1744"}}></Modal.Header>
        <AlertDialog 
          title={"Error Deleting Data"} 
          message={"There was an error deleting the Service."}
        />  
      </Modal>
    </>
  );

删除两个if语句。
如果这对你来说太混乱了,你可以把模态放在变量中进行组织。

const deleteModal = 
      <Modal show={showDelete} backdrop="static" onHide={handleClose}>
          ...
      </Modal>

const successModal = 
      <Modal show={showSuccess} onHide={() => {setShowSuccess(false); handleClose(); }} backdrop="static">
          ...
      </Modal>

const alertModal = 
      <Modal show={showAlert} onHide={() => {setShowAlert(false); handleClose(); }} backdrop="static">
          ...
      </Modal>

return (
    <>
      <Trash onClick={handleShow}/>
      {deleteModal}
      {successModal}
      {alertModal}
    </>
  );
92vpleto

92vpleto2#

在deleteService函数中调用setShow(false);这会导致隐藏模态,因为即使showSuccess为true,也要将“show”作为属性传递给Modal。
混淆是由变量名“show”造成的,该变量名没有说明有关其值的任何具体信息,因此在末尾使用不正确

相关问题