ReactQuery Pass状态将升级为按钮

发布于 2025-02-12 12:28:37 字数 826 浏览 1 评论 0原文

当单击使用useQuery触发refcter函数时,我尝试将isloadation状态传递给按钮prop,并且它不起作用(也许是因为它重新渲染组件以及组件渲染is Loading为false时)。我想知道如何使它起作用?

const MainPage: React.FC = () => {

    const {data, isLoading,  error, refetch} = useQuery<any>(
        ["getCity"],
        () => fetchCities(),
        {
                enabled: false,
            }
        )

    return (
        <div>
            <div>
                {JSON.stringify(data)}
            </div>
            <Button
                    loading={isLoading} //  always false. Need to be true when start refetch and false by the end refetch
                    label="get_cities"
                    onClick={() => refetch()}
            >

            </Button>
        </div>

    )
}

export default MainPage;

I try to pass isLoading state to button prop when click button which trigger refetch function from useQuery, and it doesn't work (maybe because it re-render component and when component render isLoading is false). I wonder how i can make it works?

const MainPage: React.FC = () => {

    const {data, isLoading,  error, refetch} = useQuery<any>(
        ["getCity"],
        () => fetchCities(),
        {
                enabled: false,
            }
        )

    return (
        <div>
            <div>
                {JSON.stringify(data)}
            </div>
            <Button
                    loading={isLoading} //  always false. Need to be true when start refetch and false by the end refetch
                    label="get_cities"
                    onClick={() => refetch()}
            >

            </Button>
        </div>

    )
}

export default MainPage;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

国际总奸 2025-02-19 12:28:37

isloading才能成为true仅当查询具有 没有数据 时,并且当前在iSfetching >如果查询在任何时候提取(包括背景恢复),将成为true

在您的情况下,只需使用iSfetching而不是isloading

const { isLoading, isFetching } = useQuery(...);

if(isLoading){
    return <div>Loading cities...</div>
}

return <Button
    loading={isFetching}
    label="get_cities"
    onClick={() => refetch()}
>

isLoading will become true only when query has no data and is currently fetching while isFetching will become true if the query is fetching at any time (including background refetching).

In your case, just use isFetching instead of isLoading

const { isLoading, isFetching } = useQuery(...);

if(isLoading){
    return <div>Loading cities...</div>
}

return <Button
    loading={isFetching}
    label="get_cities"
    onClick={() => refetch()}
>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文