reactjs 如何仅在某些参数的值发生更改时查询React查询?

tquggr8v  于 2022-11-04  发布在  React
关注(0)|答案(1)|浏览(109)

下面是我实际使用React Query的部分。
我编写了如下代码,ReactQuery不断地重新获取API。
如何仅在参数prodCode和pageable发生更改时才进行API调用?

// react-query
  const getReviewList = useQuery(
    ['getReviewList', prodCode, pageable],
    () =>
      ReviewApi.getReviewList({
        prodCode,
        pageable
      }),
    {
      enabled: !!prodCode,
      refetchOnWindowFocus: false,
      onSuccess: (data) => {
        if (!_.isUndefined(data)) {
          const copiedReviewList = reviewList.slice();
          copiedReviewList.push(...data.returnData);
          // recoil state setting
          setReviewList(copiedReviewList);
        }
      },
      onError: () => {
        setReviewList([] as Array<ReviewModel>);
      }
    }
  );
qybjjes1

qybjjes11#

React Query不会重新获取。您应该让React处理这一问题,方法是将propCodepageable作为状态变量。onSuccessonError用于数据相关的内容,因此不要更新其中的React状态变量。
我建议创建一个特定的查询类-useReviewListFetcher,然后在组件中使用它。

const useReviewListQuery = (prodCode, pageable) =>
  useQuery(
    ["getReviewList", prodCode, pageable],
    () =>
      ReviewApi.getReviewList({
        prodCode,
        pageable,
      }),
    {
      enabled: !!prodCode,
      refetchOnWindowFocus: false,
    }
  );

interface Props {
  prodCode: string;
  pageable: boolean;
}

const ReviewList = (props: Props) => {
  const reviewListQuery = useReviewListQuery(
    props.propCode,
    props.pageable
  );

  if (reviewListFetcher.data === undefined) {
    return <div>Loading.</div>;
  }

  return (
    <ul>
      {reviewListFetcher.data.map((listItem) => (
        <li>{listItem}</li>
      ))}
    </ul>
  );
};

相关问题