next.js 如何在router.push中传递查询参数,同时保持URL干净?

lymnna71  于 2023-08-04  发布在  其他
关注(0)|答案(1)|浏览(160)

我的项目在NextJS 13(不使用应用程序路由器)+ TypeScript中。
我尝试通过router.push将一些数据传递到Next.js中的动态路由页面,使用以下语法,但希望URL保持清晰,因为用户可以在URL中编辑他们的用户名。

router.push({
            pathname: `/editor/${roomId}`,
            query: { username: username, }
        }, `/editor/${roomId}`,

字符串

问题:当我被定向到/editor/roomid时,用户名确实显示了。但是当我刷新页面时,它就消失了; router.query对象中的用户名将消失**。相关代码:

relevant code from JoinRoom.tsx

import { useState } from "react";
import { nanoid } from 'nanoid';
import { useRouter } from "next/router";

interface JoinRoomProps { };

const JoinRoom = (props: JoinRoomProps) => {
    const router = useRouter();
    const [roomId, setRoomId] = useState('');
    const [username, setUsername] = useState('');
    const [isGenerated, setIsGenerated] = useState(false);

    const generateRoomId = () => {
        setRoomId(nanoid());
        setIsGenerated(true);
    };

    const joinHandler = (e: any) => {
        e.preventDefault();
        if (!roomId || !username) {
            alert('Please fill in the required fields');
            return;
        }
        router.push({
            pathname: `/editor/${roomId}`,
            query: { username: username, }
        }, `/editor/${roomId}`,
        );
    };

    return (
        <>
            // input fields for roomid, username, join room (with joinHandler)
        </>
    );
};

export default JoinRoom;


relevant code from [roomid].tsx

import { useRouter } from "next/router";

interface RoomIDProps { };

const Editor = (props: RoomIDProps) => {
    const router = useRouter();
    const { roomid, username } = router.query;

    return (
        <> 
            // display roomid and username
        </>
    )
}

// idk exactly what the below functions do, copilot came up with them:
export async function getStaticPaths() {
    return {
        paths: [
            { params: { roomid: 'test' } }
        ],
        fallback: true
    }
}

export async function getStaticProps(context: any) {
    const { roomid } = context.params;
    return {
        props: {
            roomid
        }
    }
}

export default Editor;


如何解决此问题?另外,[roomid].tsx的最后两个函数是做什么的?我最近开始使用Nextjs,所以任何相关的建议/更好的代码实践都会很有帮助。

x7rlezfr

x7rlezfr1#

更改此:

router.push({
        pathname: `/editor/${roomId}`,
        query: { username: username, }
    // remomve `/editor/${roomId}`
    // if you look at the URL, ?username=name was never added
    }, `/editor/${roomId}`,

字符串
致:

router.push({
      pathname: `/editor/${roomId}`,
      query: { username: username },
    });


这是push类型

push(url: Url, as?: Url, options?: TransitionOptions): Promise<boolean>;


这是Url类型

export type Url = UrlObject | string;


你同时传递了UrlObjectstring

相关问题