簡體   English   中英

警告:無法對未安裝的組件執行 React state 更新

[英]Warning: Can't perform a React state update on an unmounted component

我收到以下警告:“警告:無法在未安裝的組件上執行 React state 更新。這是一個空操作,但它表明您的應用程序中存在 memory 泄漏。要修復,請取消所有訂閱和異步任務在 useEffect 清理中 function。在 AddComment(位於 CommentCard.js:50)中 在 div 中(由 Comment 創建) “(CommentCard 的第 50 行是 AddComment 組件所在的行)

我有CommentCard組件,它在來自 ant 設計的Comment組件的幫助下顯示評論。 我使用 Comment 組件的 children 屬性來顯示特定評論的AddComment組件。

AddComment組件添加對評論的回復。 為了顯示相應評論的AddComment組件,我使用了一個狀態數組,並且我只為 state 等於 1 的評論顯示該組件。

添加回復后,我希望刪除AddComment組件。 為此,我在成功添加回復后更改評論的 state。 我在發布回復后立即收到警告。

這是我的 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);
        }
      }
    });
  }

您應該在卸載之前更新組件 state

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM