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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…