deltaone
V2EX  ›  Node.js

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

  •  
  •   deltaone · Jun 28, 2024 · 2199 views
    This topic created in 713 days ago, the information mentioned may be changed or developed.

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

    https://developer.mozilla.org/en-US/docs/Web/API/Response/json
    deltaone
        4
    deltaone  
    OP
       Jun 28, 2024
    多谢各位大佬,是真前端小白 @powerfulyang @onlxx123 @zed1018
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   4110 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 68ms · UTC 05:27 · PVG 13:27 · LAX 22:27 · JFK 01:27
    ♥ Do have faith in what you're doing.