【问题标题】:How to make a conditional logic using URL query in Next.JS?如何在 Next.JS 中使用 URL 查询创建条件逻辑?
【发布时间】:2021-08-26 09:31:59
【问题描述】:

我试图弄清楚如何基于 URL 查询创建条件逻辑。

在下面的示例中,我试图在 Kátia Fantes 访问 localhost:3000/katia-fantes 时动态地向她打招呼。

我该怎么做?

import { useRouter } from 'next/router'

const ClientDashboard = () => {
  const router = useRouter()
  const { clientId } = router.query
  const KF = { 'clientId': 'katia-fantes' }

  if (KF) {
    return <h1>It's Katia</h1>;
  }
  return <p>Page not found. Sorry</p>;


}

export default ClientDashboard

【问题讨论】:

  • 确保文件名为[clientId].jsnextjs.org/docs/routing/dynamic-routes
  • 另外if(kf) 没有任何意义。考虑改用if(clientId)
  • 是的,该文件名为 [clientId].js,我将 if(kf) 更改为 if (clientId) 但是...如何仅针对特定 URL 路径显示“它是 Katia”,例如 /katia-fantes ?
  • if(clientId === 'katia-fantes')?
  • 天才!呵呵谢谢!

标签: javascript reactjs next.js


【解决方案1】:

要添加到这个comment

如果您的用例仅适用于katia-fantes,那么很好。如果不是,最好把逻辑概括一下。

const { clientId } = router.query
const KF = { clientId }

  if (KF.clientId) {
    let client = KF.clientId.split('-')[0]
    client = client[0].toUpperCase() + client.splice(1)
    return <h1>It's {client}</h1>;
  }
  return <p>Page not found. Sorry</p>;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-29
    相关资源
    最近更新 更多