在带有Next.js的内容中使用UseRouter.Query值

vkc1a9a2  于 2022-10-21  发布在  其他
关注(0)|答案(1)|浏览(161)

我目前正在学习Next.js中的路由,我找不到以下代码没有在html响应中包含查询值的原因。我意识到is Ready不是真的,并且在没有设置变量的情况下返回,但我不确定如何在返回之前等待它们被设置

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

const Thread = () => {
  const router = useRouter()
  const queries = router.query;
  let communityName;
  let threadName;

  React.useEffect(()=>{
    if(router.isReady) {
      communityName = queries['community-name'].replaceAll('-', ' ');
      console.log(communityName)
      threadName = queries['thread-name'].replaceAll('-', ' ');
      console.log(threadName)
    }
  }, [router.isReady]);

  return <h1>Hello from the {communityName} Forum!<br /><br />You're receiving the thread named {threadName}!</h1>
};

export default Thread;

我点击‘http://localhost:3000/test/forum/Test-Thread’并返回以下内容:

Hello from the Forum!

You're receiving the thread named !
aiazj4mn

aiazj4mn1#

这是关于Reaction的基础知识。useEffect在渲染完成后运行。如果您更改了useEffect中的任何内容,并希望将其反映在UI中,则必须触发状态更改。
communityNamethreadName应该是状态变量。

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

const Thread = () => {
  const router = useRouter()
  const queries = router.query;
  const [communityName,setCommunityName] = useState('');
  const [threadName,setThreadName] = useState('');

  React.useEffect(()=>{
    if(router.isReady) {
      setCommunityName(queries['community-name'].replaceAll('-', ' '));
      setThreadName(queries['thread-name'].replaceAll('-', ' '));
    }
  }, [router.isReady]);

  return <h1>Hello from the {communityName} Forum!<br /><br />You're receiving the thread named {threadName}!</h1>
};

export default Thread;

相关问题