英文:
How to check if current page link contains a certain string with react component?
问题
如何检查当前页面链接是否包含特定字符串并返回true或false?
// 在这里检查页面链接是否包含"/MYSTRING/xx"
if (window.location.href.includes("/MYSTRING/xx")) {
// 如果包含,执行以下操作
}
英文:
how can i check if my current page link contains a certain string and returns true or false?
class MyDocument extends Document {
render() {
return (
<Html lang="en">
<Head>
// Check if page link contains "/MYSTRING/xx"
THEN DO THIS HERE..
</Head>
</Html>
)
}
}
答案1
得分: 1
你可以考虑2种解决方案:
解决方案1: 在NextJS中使用next/router
(我推荐这个)
import { useRouter } from 'next/router'
class MyDocument extends Document {
const { pathname } = useRouter()
render() {
return (
<Html lang="en">
<Head>
// 检查页面链接是否包含"/MYSTRING/xx"
{pathname?.includes('/MYSTRING/xx')
? `${pathname} 包含 '/MYSTRING/xx'`
: `${pathname} 不包含 '/MYSTRING/xx'`
}
</Head>
</Html>
)
}
}
解决方案2: 使用window.location.href
如果使用这种方式,您需要确保您在客户端。否则,您将看到错误 ReferenceError: window is not defined
。
这是因为在NextJS中,当页面加载时,它首先运行服务器端,但对象 window
只存在于客户端。要检测您是在服务器端还是客户端,请检查 typeof window === 'undefined'
。true
表示在服务器端,而 false
表示在客户端。
然而,这会导致服务器渲染的HTML和客户端渲染的HTML之间存在某些不匹配的情况,所以我不太推荐这种方法。
您可以在这个 代码演示 中尝试。
英文:
You can consider 2 solutions:
Solution 1: Use next/router
in NextJS (I recommend this)
import { useRouter } from 'next/router'
class MyDocument extends Document {
const { pathname } = useRouter()
render() {
return (
<Html lang="en">
<Head>
// Check if page link contains "/MYSTRING/xx"
{pathname?.includes('/MYSTRING/xx')
? `${pathname} includes '/MYSTRING/xx'`
: `${pathname} doesn't include '/MYSTRING/xx'`
}
</Head>
</Html>
)
}
}
Solution 2: Use window.location.href
If using this way, you need to ensure that you are in client-side. Otherwise, you will saw error ReferenceError: window is not defined
.
This is because in NextJS, when the page is loading, it runs the server-side first, but the object window
is only existed in client-side. To detect whether you are on server or client, please check typeof window === 'undefined'
. true
is on server while false
is on client.
However, it will lead to some case of miss match between server-rendered HTML and the client-render one, so I'm not prefer this approach.
You can play around in this code demo
答案2
得分: 0
你可以使用window.location.href
获得当前页面的URL,并使用includes()
方法检查URL是否包含你要查找的字符串,该方法返回一个布尔值。
解决方案
const lookForThisString = 'someString'
window.location.href.includes(lookForThisString) // 返回 true 或 false
英文:
You can get the current page URL returned as a string with window.location.href
and then check if the URL includes the string that you are looking for with the string includes() method which returns a boolean.
Solution
const lookForThisString = 'someString'
window.location.href.includes(lookForThisString) // returns true or false
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论