Next.js中面临的动态路由问题

2022-08-04 00:00:00 reactjs javascript html next.js jsx

所以我在Next js中有这个动态页面

import { useRouter } from 'next/router'
import { WEB_RELATED, PC_EXES } from '../../components/Data';

export default function title() {

    const router = useRouter();
    const { index } = router.query;
    
    console.log(index.length)
    
    return (
        <div>

        </div>
    )
}

在dada.long语句上,我得到错误-&>数据未定义, 我试图直接对索引执行同样的操作,但遇到了同样的问题。 我想从index参数中获取两个字符串,我该怎么做?


解决方案

您需要先测试是否定义了索引。以下是如何处理路由器查询的示例:

ps:图片下方提供的代码

PSPS:查看文档https://nextjs.org/docs/routing/dynamic-routes


// pages/testStackOverflow/[index].js

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

const Title = () => {

    const router = useRouter();

    const {index} = router.query

    // Don't use console.log directly below index because his value can be changed

    useEffect(() => {

        console.log('value', index, 'length : ', index?.length);

       // You can use if statement
      /* if(index) {
          doSomethingHere
       }*/

    // Triggering router change with useEffect
    }, [index])

    return (
        <div>
            {index}
        </div>
    )
};

export default Title;

希望我能帮助您。

相关文章