我正在构建一个电子商务平台,用户将同时使用我们的域名和他们自己的域名,如下所示。
ourplatform.com/username
theirdomain.com
我想设置内联链接取决于他们进入网站的域名。如果它是我们的域,它应该是/username/page,或者如果它是他们的域,那么它应该是/page。
这就是我到目前为止所拥有的。只有添加用户名,如果域名是我们的平台。
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>
)
}但我得到了这个错误。
Error: Failed prop type: The prop `href` expects a `string` or `object` in `<Link>`, but got `undefined` instead.如何为不同的域设置不同的href链接?
发布于 2022-04-20 01:20:49
您正确地将window.location的计算限制在客户端阶段,但是在服务器端编译阶段,仍然需要让customPath()返回<Link />组件的值。如果没有返回的值,link常量将被设置为undefined。
const customPath = ({ username }) => {
if (typeof window !== 'undefined') {
return window.location.hostname !== 'ourplatform.com' // include `.hostname`
? '/'
: `/${username}`
}
return '/' // return something to satisfy server-side compilation
}发布于 2022-04-24 17:51:29
与其直接使用typeof window !== 'undefined'访问window.location,我建议您处理useEffect中的customPath逻辑,以防止服务器端呈现不匹配。
这里有一个自定义钩子,它处理自定义路径逻辑,不抛出任何错误/警告。
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>
)
}https://stackoverflow.com/questions/71932709
复制相似问题