next.js 无法从下一个js获取id url并将其用于axios

wgx48brx  于 2023-02-15  发布在  iOS
关注(0)|答案(2)|浏览(123)

我尝试用axios发出get请求,但是没有成功,因为id const没有加载,并且被标记为未定义。

import Head from 'next/head'
import axios from 'axios'
import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/router'

export default function QuejaID() {
    const router = useRouter()
    const id = router.query.id
    console.log(id)
    const [queja, setQueja] = useState();

    useEffect(() => {
        async function request() {
            await axios.get(
                `http://localhost:3000/quejas/${id}`
            ).then((response) => {
                setQueja(response.data)
                console.log(response)
            }).catch(err => { console.log(err) })
        }
        request()
    }, []);

    return (
        <>
            <Head>
                <title>Quejas</title>
                <meta name="description" content="queja" />
                <meta name="viewport" content="width=device-width, initial-scale=1" />
                <link rel="icon" href="/favicon.ico" />
            </Head>
            <main>
                {queja ? <div className="container d-flex justify-content-center">
                    <div className="card text-center w-75 m-5">
                        <div className="card-header">{queja._id}</div>
                        <div className="card-body">
                            <h5 className="card-title">{queja.queja}</h5>
                        </div>
                        <div className="card-footer text-muted">{queja.createdAt}</div>
                    </div>
                </div> : <div>No hay ninguna queja con ese ID</div>}
            </main>
        </>
    )
}

我试了一下,但是我得到了一个axios错误,因为它是未定义的。

dldeef67

dldeef671#

id添加到依存关系数组

useEffect(() => {
        async function request() {
            await axios.get(
                `http://localhost:3000/quejas/${id}`
            ).then((response) => {
                setQueja(response.data)
                console.log(response)
            }).catch(err => { console.log(err) })
        }
        request()
    }, [id]);
wz3gfoph

wz3gfoph2#

我认为问题出在钩子useRouter上,因为你没有使用服务器端渲染,对象router.query将是一个空对象,因此router.query.id是未定义的。我建议你使用serversideprops传递id:

export default function QuejaID({id}) {
    const [queja, setQueja] = useState();

    useEffect(() => {
        async function request() {
            await axios.get(
                `http://localhost:3000/quejas/${id}`
            ).then((response) => {
                setQueja(response.data)
                console.log(response)
            }).catch(err => { console.log(err) })
        }
        request()
    }, []);

    return (
        <>
            //Your Code
        </>
    )
}

export async function getServerSideProps(context) {
  const router = useRouter()
  const id = router.query.id

  return {
    props: {id},
  }
}

相关问题