Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

reactjs - Nextjs router query parameters not logging

I am trying to log the query parameter in a Nextjs project. I never see the value logged, but the value shows up on the page. Should I just ignore that the logs in npm dev dont show the query parameter or should I handle the case where it's undefined?

/pages/test/[test].js

import {useRouter} from "next/router";
import React from "react";

const Test = () => {
    const router = useRouter();
    const {test} = router.query;
    console.log(router.query); // {}
    console.log(test);  // undefined
    return <div>
        <h1>{test}</h1>
    </div>
};
export default Test;

enter image description here

enter image description here

question from:https://stackoverflow.com/questions/65546008/nextjs-router-query-parameters-not-logging

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need use useEffect with 2 dependencies:

import {useRouter} from "next/router";
import React, {useEffect, useState} from "react";

const Test = () => {
    const router = useRouter();
    const [query, setQuery] = useState(null);

    useEffect(()=>{
      setQuery(router.query)
      if (query){
        console.log(query); 
        console.log(query.test);
      } 
    },[router,query])
    
    return <div>
        <h1>{query && query.test}</h1>
    </div>
};
export default Test;

or with one dependency:

import {useRouter} from "next/router";
import React, {useEffect} from "react";

const Test = () => {
    const router = useRouter();

    useEffect(()=>{
      if (router.query){
        console.log(router.query); 
        console.log(router.query.test);
      } 
    },[router])
    
    return <div>
        <h1>{router && router.query && router.query.test}</h1>
    </div>
};
export default Test;

When you use useEffect you are sure the router has been tuned already.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...