前端小白,咨询下 nextjs, react 项目 useQuery 相关问题,多谢各位大佬

98 天前
 deltaone

下面代码,为啥 Hello1 正常,Hello2 不正常? console.log 输出分别为: Hello1: success {Hello: 'World'} null false Hello2: undefined undefined undefined undefined

src/api/test3.tsx

'use client';

import { useQuery } from "@tanstack/react-query"
import axios from "axios"


function TestApi3() {

    return {
        Hello1,
        Hello2,
    }

    function Hello1() {
        return useQuery({
            queryKey: ["hello2"],
            queryFn: async () => {
                const { data } = await axios.get("http://localhost:8000/api/hello", )
                return data;
            }
        })
    }

    function Hello2() {
        return useQuery({
            queryKey: ['hello3'],
            queryFn: async () => {
                const data = (await fetch('http://localhost:8000/api/hello')).json()
                return data
            },
        })
    }
}

export { TestApi3 }

src/app/debug/page.tsx

'use client';

import { TestApi3 } from "@/api/test3"

export default function Home() {
    const { status, data, error, isFetching } = TestApi3().Hello1();
    console.log('Hello1:', status, data, error, isFetching)

    const { status2, data2, error2, isFetching2 } = TestApi3().Hello2();
    console.log('Hello2:', status2, data2, error2, isFetching2)


    return (
        <main className="">
            <div>
                <h1>Hello World</h1>
            </div>

        </main>
    );
}

1251 次点击
所在节点    Node.js
4 条回复
powerfulyang
98 天前
你觉得呢,变量名就不对。哪来的 status2, data2, error2, isFetching2 。
const { status as status2, data as data2 } 别名下
onlxx123
98 天前
const { status: status2, data: data2, error: error2, isFetching: isFetching2 } = TestApi3().Hello2();
zed1018
98 天前
fetch 的 response.json return type 是 promise

https://developer.mozilla.org/en-US/docs/Web/API/Response/json
deltaone
98 天前
多谢各位大佬,是真前端小白 @powerfulyang @onlxx123 @zed1018

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/1053435

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX