javascript - 警告 : Can't perform a React state update on an unmounted component. 使用Effect清理函数

标签 javascript reactjs promise

如何解决这个问题?

enter image description here

//ReviewProductDetail.jsx :

第一次从这个组件中取出页面

import React, { useEffect, useState } from 'react';
import RatingCardProductDetail from '../../components/RatingCardProductDetail';
import "./style.sass";
import FilterReviewProductDetail from '../../components/FilterReviewProductDetail';
import { Row, Col, Pagination, Spin } from 'antd';
import LatestReview from '../../components/LatestReview';
import strings from '../../localization/localization';
import Product from '../../repository/Product';

function ReviewProductDetail({ productId }) {
    const [reviewRatingDetail, setReviewRatingDetail] = useState({})
    const [reviewRating, setReviewRating] = useState([])
    const [notFound, setNotFound] = useState(false)
    const [loading,setLoading] = useState(false)

    useEffect(() => {
        getReviewRatingDetail();
        getReviewRating();
    }, [])


    async function getReviewRatingDetail() {
        let reviewRatingDetail = await Product.reviewRatingDetail({
            productId: productId
        })
        if (reviewRatingDetail.status === 200) {
            setReviewRatingDetail(reviewRatingDetail)
        } else {
            setReviewRatingDetail({})
        }
    }

    async function getReviewRating() {
        let reviewRating = await Product.reviewRating({
            productId: productId,
            loading: setLoading
        })
        if (reviewRating.status === 200) {
            setReviewRating(reviewRating)
            setNotFound(false)
        } else {
            setReviewRating([])
            setNotFound(true)
        }
    }

    return (
        <Spin spinning={loading}>
            <div className="mp-review-product-detail">
                {notFound ?
                    <div className="mp-product-detail__not-found">
                        <span>
                            Belum ada ulasan untuk produk ini
                        </span>
                    </div> :
                    <React.Fragment>
                        <RatingCardProductDetail reviewRatingDetail={reviewRatingDetail} />
                        <Row>
                            <Col md={17} offset={3}>
                                <div className="mp-review-product-detail__filter">
                                    <FilterReviewProductDetail />
                                </div>
                            </Col>
                        </Row>
                        <h3>{strings.latest_review}</h3>
                        {reviewRating.review &&
                            reviewRating.review.map((review, i) => {
                                return <LatestReview key={i} review={review} />
                            })}
                        <Pagination
                            className="mp-pagination-review-product-detail"
                            defaultCurrent={1}
                            total={5} />
                    </React.Fragment>}
            </div>
        </Spin>
    );
}; 

export default ReviewProductDetail;

那么这是一个调用数据API的组件,

async function reviewRatingDetail(props) {
  const loading = props.loading ? props.loading : function () { };
  const productId = props.productId;
  // const decodeURL = decodeURI(productId)
  const idProduct = productId.replace(/ /g, '')
  let response = "";
  loading(true);
  try {
    response = await apiGetWithoutToken(`${PATH_PRODUCT.PRODUCT}/${idProduct}/${PATH_PRODUCT.PRODUCT_REVIEW_RATING_DETAIL}`);
    response = jmespath.search(response, productsReviewDetail);
    loading(false);
  } catch (error) {
    response = jmespath.search(error.response, productsReviewDetail);
    loading(false);
  }
  return response;
}

async function reviewRating(props) {
  const loading = props.loading ? props.loading : function () { };
  const productId = props.productId;
  //const decodeURL = decodeURI(productId);
  const idProduct = productId.replace(/ /g, '');
  let response = "";
  loading(true);
  try {
    response = await apiGetWithoutToken(`${PATH_PRODUCT.PRODUCT}/${idProduct}/${PATH_PRODUCT.PRODUCT_REVIEW}`);
    response = jmespath.search(response, productsReview);
    loading(false);
  } catch (error) {
    response = jmespath.search(error.response, productsReview);
    loading(false);
  }
  return response;
}

/** Service Without Token api getWithoutToken */


export const apiGetWithoutToken = (url, params = null) => {
  return serviceWithoutToken().get(url, {
    params: params
  });
};

export const serviceWithoutToken = () => axios.create({
  baseURL: REACT_APP_API_SERVICE,
  timeout: 60 * 4 * 1000,
  headers: {
    "Content-Type": `application/json`,
  }
});

想求助各位,如何去除这些错误标记。请直接举个例子谢谢

最佳答案

尝试使用Effect添加这个:

useEffect(() => {
    getReviewRatingDetail();
    getReviewRating();
}, [productId])

或在整个函数 ReviewProductDetail 上使用 useCallback ( https://reactjs.org/docs/hooks-reference.html#usecallback )

关于javascript - 警告 : Can't perform a React state update on an unmounted component. 使用Effect清理函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58266157/

相关文章:

select - 如何使用数组作为 react 选择组件的选项

javascript - 如何使这个异步 foreach 循环与 promises 一起工作?

javascript - 链接 Promise 并在它们之间传递参数

javascript - Promise.then() 在第一次单击按钮时不起作用

javascript - 如何访问装饰器中的 ngStyle 键和值?

javascript - 计时器不倒计时

json - 在react render方法中访问对象属性

javascript - React JS 不适用于 Internet Explorer 9

javascript - 两个Web组件之间的绑定(bind): Google map + geo-localisation

javascript - 将新项目推送到 mongoDB 文档数组