V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
deltaone
V2EX  ›  Node.js

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

  •  
  •   deltaone · 7 天前 · 702 次点击

    下面代码,为啥 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>
        );
    }
    
    
    4 条回复    2024-06-28 19:09:57 +08:00
    powerfulyang
        1
    powerfulyang  
       7 天前
    你觉得呢,变量名就不对。哪来的 status2, data2, error2, isFetching2 。
    const { status as status2, data as data2 } 别名下
    onlxx123
        2
    onlxx123  
       7 天前
    const { status: status2, data: data2, error: error2, isFetching: isFetching2 } = TestApi3().Hello2();
    zed1018
        3
    zed1018  
       7 天前
    fetch 的 response.json return type 是 promise

    https://developer.mozilla.org/en-US/docs/Web/API/Response/json
    deltaone
        4
    deltaone  
    OP
       7 天前
    多谢各位大佬,是真前端小白 @powerfulyang @onlxx123 @zed1018
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2359 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 00:10 · PVG 08:10 · LAX 17:10 · JFK 20:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.