首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用Next.js处理内联URL

用Next.js处理内联URL
EN

Stack Overflow用户
提问于 2022-04-20 00:14:53
回答 2查看 352关注 0票数 1

我正在构建一个电子商务平台,用户将同时使用我们的域名和他们自己的域名,如下所示。

ourplatform.com/username

theirdomain.com

我想设置内联链接取决于他们进入网站的域名。如果它是我们的域,它应该是/username/page,或者如果它是他们的域,那么它应该是/page

这就是我到目前为止所拥有的。只有添加用户名,如果域名是我们的平台。

代码语言:javascript
复制
import Link from 'next/link'

const customPath = ({ username }) => {
  if (typeof window !== 'undefined') {
    return window.location !== 'ourplatform.com'
      ? '/'
      : `/${username}`
  }
}

export default ({ username }) => {
  const link = customPath({ username })
  return (
    <Link href={link}>
      Home
    </Link>
  )
}

但我得到了这个错误。

代码语言:javascript
复制
Error: Failed prop type: The prop `href` expects a `string` or `object` in `<Link>`, but got `undefined` instead.

如何为不同的域设置不同的href链接?

EN

回答 2

Stack Overflow用户

发布于 2022-04-20 01:20:49

您正确地将window.location的计算限制在客户端阶段,但是在服务器端编译阶段,仍然需要让customPath()返回<Link />组件的值。如果没有返回的值,link常量将被设置为undefined

代码语言:javascript
复制
const customPath = ({ username }) => {
  if (typeof window !== 'undefined') {
    return window.location.hostname !== 'ourplatform.com' // include `.hostname`
      ? '/'
      : `/${username}`
  }
  return '/' // return something to satisfy server-side compilation
}
票数 1
EN

Stack Overflow用户

发布于 2022-04-24 17:51:29

与其直接使用typeof window !== 'undefined'访问window.location,我建议您处理useEffect中的customPath逻辑,以防止服务器端呈现不匹配。

这里有一个自定义钩子,它处理自定义路径逻辑,不抛出任何错误/警告。

代码语言:javascript
复制
import Link from 'next/link'

function useCustomPath({ username }) {
    const [customPath, setCustomPath] = useState('/') // Default path during SSR

    useEffect(() => {
        const path = window.location.hostname !== 'ourplatform.com' ? '/' : `/${username}`
        setCustomPath(path) // Set appropriate path on the client-side
    }, [username])

    return customPath
}

export default ({ username }) => {
    const link = useCustomPath({ username })
    
    return (
        <Link href={link}>
            Home
        </Link>
    )
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71932709

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档