我的项目在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,所以任何相关的建议/更好的代码实践都会很有帮助。
1条答案
按热度按时间x7rlezfr1#
更改此:
字符串
致:
型
这是
push
类型型
这是
Url
类型型
你同时传递了
UrlObject
和string