Programing

경고:마운트 해제된 구성 요소에 대해 반응 상태 업데이트를 수행할 수 없음

c10106 2022. 3. 29. 21:12
반응형

경고:마운트 해제된 구성 요소에 대해 반응 상태 업데이트를 수행할 수 없음

다음과 같은 경고를 받고 있다: "경고: 마운트 해제된 구성 요소에 대해 반응 상태 업데이트를 수행할 수 없음 이것은 작동 불가지만, 당신의 어플리케이션에 메모리 누수가 있다는 것을 나타낸다. 수정하려면 useEffect 정리 함수의 모든 구독 및 비동기 작업을 취소하십시오. Div(Comment에 의해 작성됨) AddComment(CommentCard.js:50)에서(CommentCard에서 50행은 AddComment 구성 요소가 있는 라인임)

나는 개미 디자인의 Comment 구성 요소의 도움을 받아 코멘트를 표시하는 CommentCard 구성 요소를 가지고 있다.특정 코멘트에 대한 AddComment 구성 요소를 표시하기 위해 Comment 구성 요소의 하위 속성을 사용한다.

AddComment 구성 요소는 코멘트에 응답을 추가한다.해당 주석에 대한 AddComment 구성 요소를 표시하기 위해 상태 배열을 사용하고 있으며 상태가 1인 주석에 대해서만 구성 요소를 표시한다.

응답을 추가한 후 AddComment 구성 요소를 제거하십시오.이를 위해 회신이 성공적으로 추가된 후 주석 상태를 변경한다.답장을 올리면 바로 경고를 받고 있어.

CommentCard 구성 요소

function CommentCard(props) {
  const [hasReplyCommentBox, setHasReplyCommentBox] = useState([]);
  const { t } = useTranslation();

  const commentStyle = {
    padding: '10px',
    backgroundColor: 'white',
    'whiteSpace': 'pre',
    width: '100%'
  };

  function toggleReplyBoxVisibility(commentIndex) {
    var auxState = { ...hasReplyCommentBox };
    auxState[commentIndex] = auxState[commentIndex] ? 0 : 1;
    setHasReplyCommentBox(auxState);
  }

  const actions = [
    <span
      id={"reply-button-" + props.commentIndex}
      onClick={() => toggleReplyBoxVisibility(props.commentIndex)}>
      {t('Reply to')}
    </span>
  ];

  const commentReplyBox = (
    hasReplyCommentBox[props.commentIndex]
      ? <AddComment
          id={props.codeId}
          parentCommentId={props.parentCommentId}
          commentIndex={props.commentIndex}
          toggleReplyBoxVisibility={toggleReplyBoxVisibility}
          updateComments={props.updateComments}
        />
      : null
  );

  return (
    <Comment
      author={props.userId}
      datetime={props.datePosted}
      content={props.body}
      actions={actions}
      children={commentReplyBox}
      style={commentStyle}
    />
  );
}

내 AddComment 구성 요소:

function AddComment(props) {
  const { t } = useTranslation();
  const { TextArea } = Input;
  const [form] = Form.useForm();
  const [comment, setComment] = useState();

  const buttonStyle = { float: 'right' };

  function onCommentChange(newComment) {
    setComment(newComment.target.value);
  }

  function resetCommentInput() {
    setComment('');
  }

  function onFormReset() {
    form.resetFields();
  }

  function submitComment() {
    let request = {
      body: comment,
      code_id: props.id,
      line_number: props.lineNumber,
      parent_comment_id: props.parentCommentId
    };
    fetch('/api/comment/add',
      {
        method: 'POST',
        body: JSON.stringify(request)
      }
    ).then(response => response.json())
    .then(data => {
      if (data.success === 1) {
        if (props.parentCommentId) {
          props.toggleReplyBoxVisibility(props.commentIndex);
        }
        props.updateComments();
        resetCommentInput();
      }
    });
  }

  return (
    <>
      <Form form={form} name="comment" className="comment-form"
        onFinish={submitComment}
        id={"add-comment-form" + props.parentCommentId}>
        <Form.Item name="body" label={t('Comment')}>
          <TextArea placeholder={t('Leave a comment')}
            onChange={onCommentChange}
            id={getCommentTextAreaId(props.lineNumber, props.parentCommentId)}
          />
        </Form.Item>
        <Form.Item style={buttonStyle}>
          <Space>
            <Button type="primary" htmlType="submit"
              id={
                getPostCommentButtonId(props.lineNumber, props.parentCommentId)
              }
              className = "comment-form-button" onClick={onFormReset}>
              {t('Post')}
            </Button>
            {props.parentCommentId
              ? <Button id={"cancel-add-reply-comment-" + props.parentCommentId}
                  type="secondary" className="comment-form-button"
                  onClick={
                    () => props.toggleReplyBoxVisibility(props.commentIndex)
                  }>
                  {t('Cancel')}
                </Button>
              : null
            }
          </Space>
        </Form.Item>
      </Form>
    </>
  );
}

이것을 사용해 보십시오.

function submitComment() {
    let request = {
      body: comment,
      code_id: props.id,
      line_number: props.lineNumber,
      parent_comment_id: props.parentCommentId
    };
    fetch('/api/comment/add',
      {
        method: 'POST',
        body: JSON.stringify(request)
      }
    ).then(response => response.json())
    .then(data => {
      if (data.success === 1) {
        props.updateComments();
        resetCommentInput();
        // Run resetCommentInput before props.toggleReplyBoxVisibility
        if (props.parentCommentId) {
          props.toggleReplyBoxVisibility(props.commentIndex);
        }
      }
    });
  }

구성 요소를 마운트 해제하기 전에 먼저 구성 요소 상태를 업데이트하십시오.

참조URL: https://stackoverflow.com/questions/64804801/warning-cant-perform-a-react-state-update-on-an-unmounted-component

반응형