reactjs React-query useQuery执行多次

q35jwt9p  于 2023-05-17  发布在  React
关注(0)|答案(1)|浏览(318)

我有一个执行多个API调用的页面-fetchPreviousOverallStatus
当用户单击Card时,将打开一个modal并进行另一个API调用-fetchPreviousData
我注意到初始API调用(fetchPreviousOverallStatus)被多次调用。甚至当我清除来自Chrome的网络请求时。
我想做的是,当用户到达一个页面时,只调用几个API一次,然后如果用户单击一个Card,则调用其他API,这将打开一个模态并显示结果。
我在没有react-query的情况下可以使用这个库,但我想使用这个库的其他功能。

import React, {useState, useEffect, useMemo} from "react"
import Card from "../Common/Card"
import {useSelector} from "react-redux"
import Overlay from "../Common/Overlay"
import axios from "axios"
import {apiSubDirectory} from "../../Constants"
import {useQueryClient, useQuery} from "react-query"

export default function OverallOrderCommunicationServiceStatus() {

    const onSuccess = (data) => {
        console.log("Perform side effect after success", data.data)
    }
    const onError = (error) => {
        console.log('Perform side effect after error', error)
    }

    const [isOpen, setIsOpen] = useState(false);
    const [dataToFetch, setDataToFetch] = useState("");
    const [apiData, setApiData] = useState([]);

    const environmentMapping = useSelector(
        (state) => state.env.environmentMapping
    );

    const queryClient = useQueryClient();

    const urlOverallPreviousStatus = `https://jsonplaceholder.typicode.com/posts`

    const fetchPreviousOverallStatus = () => { return axios.get(urlOverallPreviousStatus) }

    const { isLoading, data, isError, error, isFetching, refetch } = useQuery('overallPreviousStatus', fetchPreviousOverallStatus, {
        onSuccess,
        onError,
        enabled: true
    })

    const fetchPreviousOcsTestResults = () => {
        return axios.get(`https://jsonplaceholder.typicode.com/posts?a=${environmentMapping[0].previous.environment}`)
    }

    const { isLoading:isLoading1, data:data1, isError:isError1, error:error1, isFetching:isFetching1 } = useQuery('previousOcsTestResults', fetchPreviousOcsTestResults, {
        onSuccess,
        onError,
        enabled: false
    })

    const fetchPreviousData = async () => {
        await queryClient.refetchQueries('previousOcsTestResults');
    };

    useEffect(() => {
        if (isOpen) {
            if (dataToFetch === "previous") {
                fetchPreviousData();
            }
        }
    }, [isOpen]);

    const columns = useMemo(() => [
        {
            Header: "Status",
            accessor: "title",
        },
    ], [])

    const handlePopupOpen = (dataToFetch) => {
        setIsOpen(true);
        setDataToFetch(dataToFetch);
    };

    const handlePopupClose = () => {
        setIsOpen(false);
    };

    return (
        <React.Fragment>
            <div className="row">
                <div className="col-md-12 ml-sm-auto col-lg-12 mt-5">
                    <div className="row mt-5">
                        <div className="card-group">
                            <Card
                                environmentName={environmentMapping[0].previous.environment}
                                releaseno="Environment"
                                onClick={() => handlePopupOpen("previous")}
                            />

                            {environmentMapping[0].previous.isEnvironmentReady ? (

                                isOpen && (
                                    <Overlay
                                        environment={environmentMapping[0].previous.environment}
                                        //release_overlay={modal}
                                        onClose={handlePopupClose}
                                        show={isOpen}
                                        columns={columns}
                                        apiData={apiData}
                                    />
                                )
                            ) : (
                                <React.Fragment />
                            )}

                        </div>
                    </div>
                </div>
            </div>
        </React.Fragment>
    );
}

我试过了,没有运气:

useEffect(() => {
        return () => {
            // Disable the query when the component unmounts
            queryClient.getQueryCache().getQuery('overallPreviousStatus').setState({ enabled: false });
        };
    }, []);
km0tfn4u

km0tfn4u1#

我注意到初始API调用(fetchPreviousOverallStatus)被多次调用。甚至当我清除来自Chrome的网络请求时。
React Query默认在窗口焦点上重新获取过时的查询。当你切换到chrome devtools来清除网络请求的时候,你的注意力就已经离开了浏览器窗口。然后,当你回到它,一个窗口焦点事件将被触发。
默认情况下,只有过时的查询才会被重新获取,因此如果您对默认值staleTime: 0不满意,最好的解决方案是为资源设置一个staleTime。
另请阅读:

相关问题