useRouter issue in next.js



我已经分解了这个问题,看到它来自y[1]中的1。TypeError:无法读取未定义的属性(读取'1')。我通常没有这样的代码但我确实为了拆卸来发现问题。更多的上下文,它有时会起作用,console.log(y)返回它数组(2)0:"chatid"1:"id">

const router = useRouter()
const chatidx = (Object.entries(router.query));
const y = (chatidx[0]);
console.log(y)
console.log(y[1]);

我怀疑你在URL上没有任何查询参数。

你应该检查你的URL如下或不

test.com/?chatid=id

下面是如何从上面的URL

返回router.query
{chatid: "id"}

如果没有这些,router.query的默认值将是{},这会导致您面临的错误

const router = useRouter()
const chatidx = (Object.entries(router.query)); //convert to []
const y = (chatidx[0]); //no `[0]` value, so it's `undefined`
console.log(y) //undefined
console.log(y[1]); //ERROR - try to get `[1]` of an undefined value

最新更新