从ssr上的url参数中获取带有id的数据



我想从fetch中获取数据,但fetch中的一个参数是来自实际URL的参数。我用的是Nextjs

下面是我的代码:
const Room = () => {
let fetchData;
let roomId;
const getID = () => {
const router = useRouter();
const { id } = router.query;
roomId = id;
console.log("ID + " + roomId);
};
const getDataNames = () => {
try {
fetch("http://localhost:1337/rooms?_id=" + roomId)
.then((response) => response.json())
.then((data) => (fetchData = data));
} catch (e) {
console.error(e);
}
};
getID();
getDataNames();
return (
<div>
<p>{roomId}</p>
<p>{fetchData}</p>
</div>
);
};

首先我调用getID(),它给我未定义,然后被称为getDataNames(),但在url是未定义的参数,因为roomId是未定义的。

我不知道该怎么修复它。但我也不明白的是为什么函数被调用两次。控制台日志

在React中不鼓励调用组件内部的函数。最好使用像useEffect这样的钩子。所以如果你想在组件加载时调用getID()getDataNames(),你可以这样写:

useEffect(() => {
getID();
getDataNames();
}, []);

这样你就可以确保函数只被调用一次。

不仅如此,我还会这样修改你的代码:

const Room = () => {
const router = useRouter();

useEffect(() => {
if (router.asPath !== router.route) {
getDataNames();
}
}, [router]);

const getDataNames = () => {
try {
fetch("http://localhost:1337/rooms?_id=" + router.query.id)
.then((response) => response.json())
.then((data) => (fetchData = data));
} catch (e) {
console.error(e);
}
};
...

这样就不需要getID()函数了。

最新更新