尝试更新状态,但初始值仍记录在React中

问题描述 投票:0回答:1

我试图在用户删除其评论后更新变量的状态以显示模式(弹出窗口),但该变量永远不会更新。我使用

useState
钩子来更新状态,但由于它是异步性质,因此使用初始值,因此模态永远不会显示。我阅读了其他建议使用
useEffect
钩子的解决方案,但仍然没有运气。

删除评论.tsx:

import { deleteComment } from "../../utils/api";

import React, { useState, useEffect } from "react";

import { MessageModal, ResultModal } from "../Modal";

type Comment = {
  author: string;
  comment_id: string;
};
type Props = {
  comment: Comment;
  onDelete: Function;
};

export default function DeleteCommentById({ comment, onDelete }: Props) {
  const [showModal, setShowModal] = useState(false);
  const [showResultModal, setShowResultModal] = useState(false);
  console.log(showResultModal)

  useEffect(() => {
    if (showResultModal) {
      console.log('changed')
    } else {
      console.log('no change')
    }
  },[showResultModal])

  const handleDelete = async (e: any) => {
    e.preventDefault();

    try {
      if (window.sessionStorage.getItem("user") === comment.author) {
        setShowModal(false);
        onDelete(comment.comment_id);
        await deleteComment(comment.comment_id);
        setShowResultModal(true)
      }
    } catch (err) {
      setShowResultModal(true)
      console.log(err);
    }
  };

  return (
    <>
      <MessageModal
        show={showModal}
        onClose={() => setShowModal(false)}
        title="Confirm"
        message="Are you sure you want to delete this comment?"
        onConfirm={handleDelete}
      />
    <ResultModal show={showResultModal} onClose={() => setShowResultModal(false)} title={'resultTitle'} message={'resultMessage'} />
      <button onClick={() => setShowModal(true)}>Delete</button>
    </>
  );
}

模态.tsx:

import Modal from "react-bootstrap/Modal";
import Button from 'react-bootstrap/Button';
import React from "react";

type MessageModalProps = {
  show: boolean;
  onClose: () => void;
  title: string;
  message: string;
  onConfirm: any;
};

export const MessageModal: React.FC<MessageModalProps> = ({ show, onClose, title, message, onConfirm }) => {
  return (
    <Modal show={show}>
      <Modal.Header>
        <Modal.Title>{title}</Modal.Title>
      </Modal.Header>
      <Modal.Body>{message}</Modal.Body>
      <Modal.Footer>
        <Button variant="secondary" onClick={onClose}>Cancel</Button>
        <Button variant="primary" onClick={onConfirm}>Confirm</Button>
      </Modal.Footer>
    </Modal>
  );
};

type ResultModalProps = {
  show: boolean;
  onClose: () => void;
  title: string;
  message: string;
};

export const ResultModal: React.FC<ResultModalProps> = ({ show, onClose, title, message }) => {
  return (
    <Modal show={show}>
      <Modal.Header>
        <Modal.Title>{title}</Modal.Title>
      </Modal.Header>
      <Modal.Body>{message}</Modal.Body>
      <Modal.Footer>
        <button className="btn btn-primary" onClick={onClose}>
          Close
        </button>
      </Modal.Footer>
    </Modal>
  );
};

api函数:

export const deleteComment = (id: string) => {
  return axios
    .delete(
      `localhost/api/comments/${id}`
    )
    .then(() => {
      console.log(`Deleted comment ${id}`);
    })
    .catch((err) => {
      console.log(err.response.data);
    });
};
javascript reactjs typescript
1个回答
0
投票

你的问题不清楚。但我建议首先检查您的

comment.author
检查是否在
handleDelete
函数内部返回 true。然后检查所有其他行是否有帮助。祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.