警告:无法在已卸载的组件上执行React状态更新。 useEffect清理功能

时间:2019-10-07 08:47:37

标签: 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;
}

/ **没有令牌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`,
  }
});

我想寻求您的帮助,如何摆脱这些错误标记。请直接举个例子谢谢

1 个答案:

答案 0 :(得分:2)

尝试使用效果添加此内容:

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

或整个功能ReviewProductDetail上使用useCallback(https://reactjs.org/docs/hooks-reference.html#usecallback