javascript 如何在Reactjs中使用基于url的条件

q3aa0525  于 2023-01-19  发布在  Java
关注(0)|答案(5)|浏览(112)

我正在使用Reactjs和nextjs框架,现在我想如果网址包含“?id=pinned”,那么不同的文本应该显示,我怎么能做到这一点?这里是我目前在[slug.js]的代码

return(
        if(url containing pinned)
        {
            <div id="neww" className="neww"><h3>Pinned</h3></div>
        }
        else
        {
         <div id="neww" className="neww"><h3>Newest</h3></div>
        }
)
1qczuiv0

1qczuiv01#

由于您似乎使用的是Next.js,因此可以使用API来完成此操作

import { useRouter } from 'next/router'

const Post = () => {
  const router = useRouter()
  const { id } = router.query
  const isPinned = id === 'pinned'
  
  if (isPinned) {
     return (<div id="neww" className="neww"><h3>Pinned</h3></div>)
  } else {
     return (<div id="neww" className="neww"><h3>Newest</h3></div>)
  }
}
xqnpmsa8

xqnpmsa82#

忽略,否则应尝试使用三元运算符

return(
        <div id="neww" className="neww">
          <h3> 
            {(url.includes('pinned') ? "Pinned":"Newest" }                         
          </h3>
       </div>
)
iqjalb3h

iqjalb3h3#

您可以从路由器使用查询
示例

const router = useRouter();
const {id} = router.query;

return(
        if(id === "pinned")
        {
            <div id="neww" className="neww"><h3>Pinned</h3></div>
        }
        else
        {
         <div id="neww" className="neww"><h3>Newest</h3></div>
        }
)
ffvjumwh

ffvjumwh4#

下面是一个方法:

import { useRouter } from "next/router";

  const router = useRouter();
  const id = router.query["id"];
  return(
        if(id === "pinned")
        {
            <div id="neww" className="neww"><h3>Pinned</h3></div>
        }
        else
        {
         <div id="neww" className="neww"><h3>Newest</h3></div>
        }
)
uxh89sit

uxh89sit5#

请执行以下操作:

import { useRouter } from 'next/router'

const Post = () => {
  const {query} = useRouter()
  const isPinned = query.id === 'pinned'
  return (<div id="neww" className="neww">
           <h3>{isPinned ? 'Pinned': 'Newest'}</h3>
         </div>)
}

相关问题