未验证 提交 dd97c984 编写于 作者: J Jan Potoms 提交者: GitHub

Convert link to function component (#14633)

Convert `Link` to a function component. Prefetch logic and memoized url formatting now meshes nicely with React hooks. Class methods were hoisted to module scope to preserve performance characteristics.
上级 dc49cd33
declare const __NEXT_DATA__: any
import React, { Children, Component } from 'react'
import React, { Children } from 'react'
import { parse, resolve, UrlObject } from 'url'
import { PrefetchOptions } from '../next-server/lib/router/router'
import {
......@@ -22,24 +22,6 @@ function isLocal(href: string): boolean {
}
type Url = string | UrlObject
type FormatResult = { href: string; as?: string }
function memoizedFormatUrl(formatFunc: (href: Url, as?: Url) => FormatResult) {
let lastHref: null | Url = null
let lastAs: undefined | null | Url = null
let lastResult: null | FormatResult = null
return (href: Url, as?: Url) => {
if (lastResult && href === lastHref && as === lastAs) {
return lastResult
}
const result = formatFunc(href, as)
lastHref = href
lastAs = as
lastResult = result
return result
}
}
function formatUrl(url: Url): string {
return (
......@@ -114,203 +96,181 @@ const listenToIntersections = (el: Element, cb: () => void) => {
}
}
class Link extends Component<LinkProps> {
p: boolean
function getPaths(parsedHref: string, parsedAs?: string): string[] {
const { pathname } = window.location
const resolvedHref = resolve(pathname, parsedHref)
return [resolvedHref, parsedAs ? resolve(pathname, parsedAs) : resolvedHref]
}
constructor(props: LinkProps) {
super(props)
function prefetch(href: string, as?: string, options?: PrefetchOptions): void {
if (typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client)
const [resolvedHref, resolvedAs] = getPaths(href, as)
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
Router.prefetch(resolvedHref, resolvedAs, options).catch((err) => {
if (process.env.NODE_ENV !== 'production') {
if (props.prefetch) {
console.warn(
'Next.js auto-prefetches automatically based on viewport. The prefetch attribute is no longer needed. More: https://err.sh/vercel/next.js/prefetch-true-deprecated'
)
}
// rethrow to show invalid URL errors
throw err
}
this.p = props.prefetch !== false
}
cleanUpListeners = () => {}
})
// Join on an invalid URI character
prefetched[resolvedHref + '%' + resolvedAs] = true
}
componentWillUnmount(): void {
this.cleanUpListeners()
function linkClicked(
e: React.MouseEvent,
href: string,
as?: string,
replace?: boolean,
shallow?: boolean,
scroll?: boolean
): void {
const { nodeName, target } = e.currentTarget as HTMLAnchorElement
if (
nodeName === 'A' &&
((target && target !== '_self') ||
e.metaKey ||
e.ctrlKey ||
e.shiftKey ||
(e.nativeEvent && e.nativeEvent.which === 2))
) {
// ignore click for new tab / new window behavior
return
}
getPaths(): string[] {
const { pathname } = window.location
const { href: parsedHref, as: parsedAs } = this.formatUrls(
this.props.href,
this.props.as
)
const resolvedHref = resolve(pathname, parsedHref)
return [resolvedHref, parsedAs ? resolve(pathname, parsedAs) : resolvedHref]
if (!isLocal(href)) {
// ignore click if it's outside our scope (e.g. https://google.com)
return
}
handleRef(ref: Element): void {
if (this.p && IntersectionObserver && ref && ref.tagName) {
this.cleanUpListeners()
const { pathname } = window.location
href = resolve(pathname, href)
as = as ? resolve(pathname, as) : href
const isPrefetched =
prefetched[
this.getPaths().join(
// Join on an invalid URI character
'%'
)
]
if (!isPrefetched) {
this.cleanUpListeners = listenToIntersections(ref, () => {
this.prefetch()
})
}
}
}
e.preventDefault()
// The function is memoized so that no extra lifecycles are needed
// as per https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html
formatUrls = memoizedFormatUrl((href, asHref) => {
return {
href: formatUrl(href),
as: asHref ? formatUrl(asHref) : asHref,
}
})
// avoid scroll for urls with anchor refs
if (scroll == null) {
scroll = as.indexOf('#') < 0
}
linkClicked = (e: React.MouseEvent): void => {
const { nodeName, target } = e.currentTarget as HTMLAnchorElement
if (
nodeName === 'A' &&
((target && target !== '_self') ||
e.metaKey ||
e.ctrlKey ||
e.shiftKey ||
(e.nativeEvent && e.nativeEvent.which === 2))
) {
// ignore click for new tab / new window behavior
return
// replace state instead of push if prop is present
Router[replace ? 'replace' : 'push'](href, as, { shallow }).then(
(success: boolean) => {
if (!success) return
if (scroll) {
window.scrollTo(0, 0)
document.body.focus()
}
}
)
}
let { href, as } = this.formatUrls(this.props.href, this.props.as)
if (!isLocal(href)) {
// ignore click if it's outside our scope (e.g. https://google.com)
return
function Link(props: React.PropsWithChildren<LinkProps>) {
if (process.env.NODE_ENV !== 'production') {
// This hook is in a conditional but that is ok because `process.env.NODE_ENV` never changes
// eslint-disable-next-line react-hooks/rules-of-hooks
const hasWarned = React.useRef(false)
if (props.prefetch && !hasWarned.current) {
hasWarned.current = true
console.warn(
'Next.js auto-prefetches automatically based on viewport. The prefetch attribute is no longer needed. More: https://err.sh/vercel/next.js/prefetch-true-deprecated'
)
}
}
const p = props.prefetch !== false
const { pathname } = window.location
href = resolve(pathname, href)
as = as ? resolve(pathname, as) : href
const [childElm, setChildElm] = React.useState<Element>()
e.preventDefault()
const { href, as } = React.useMemo(
() => ({
href: formatUrl(props.href),
as: props.as ? formatUrl(props.as) : props.as,
}),
[props.href, props.as]
)
// avoid scroll for urls with anchor refs
let { scroll } = this.props
if (scroll == null) {
scroll = as.indexOf('#') < 0
React.useEffect(() => {
if (p && IntersectionObserver && childElm && childElm.tagName) {
const isPrefetched =
prefetched[
// Join on an invalid URI character
getPaths(href, as).join('%')
]
if (!isPrefetched) {
return listenToIntersections(childElm, () => {
prefetch(href, as)
})
}
}
}, [p, childElm, href, as])
// replace state instead of push if prop is present
Router[this.props.replace ? 'replace' : 'push'](href, as, {
shallow: this.props.shallow,
}).then((success: boolean) => {
if (!success) return
if (scroll) {
window.scrollTo(0, 0)
document.body.focus()
}
})
let { children, replace, shallow, scroll } = props
// Deprecated. Warning shown by propType check. If the children provided is a string (<Link>example</Link>) we wrap it in an <a> tag
if (typeof children === 'string') {
children = <a>{children}</a>
}
prefetch(options?: PrefetchOptions): void {
if (!this.p || typeof window === 'undefined') return
// Prefetch the JSON page if asked (only in the client)
const paths = this.getPaths()
// We need to handle a prefetch error here since we may be
// loading with priority which can reject but we don't
// want to force navigation since this is only a prefetch
Router.prefetch(paths[/* href */ 0], paths[/* asPath */ 1], options).catch(
(err) => {
if (process.env.NODE_ENV !== 'production') {
// rethrow to show invalid URL errors
throw err
// This will return the first child, if multiple are provided it will throw an error
const child: any = Children.only(children)
const childProps: {
onMouseEnter?: React.MouseEventHandler
onClick: React.MouseEventHandler
href?: string
ref?: any
} = {
ref: (el: any) => {
setChildElm(el)
if (child && typeof child === 'object' && child.ref) {
if (typeof child.ref === 'function') child.ref(el)
else if (typeof child.ref === 'object') {
child.ref.current = el
}
}
)
prefetched[
paths.join(
// Join on an invalid URI character
'%'
)
] = true
},
onClick: (e: React.MouseEvent) => {
if (child.props && typeof child.props.onClick === 'function') {
child.props.onClick(e)
}
if (!e.defaultPrevented) {
linkClicked(e, href, as, replace, shallow, scroll)
}
},
}
render() {
let { children } = this.props
let { href, as } = this.formatUrls(this.props.href, this.props.as)
as = as ? addBasePath(as) : as
href = addBasePath(href)
// Deprecated. Warning shown by propType check. If the children provided is a string (<Link>example</Link>) we wrap it in an <a> tag
if (typeof children === 'string') {
children = <a>{children}</a>
if (p) {
childProps.onMouseEnter = (e: React.MouseEvent) => {
if (child.props && typeof child.props.onMouseEnter === 'function') {
child.props.onMouseEnter(e)
}
prefetch(href, as, { priority: true })
}
}
// This will return the first child, if multiple are provided it will throw an error
const child: any = Children.only(children)
const props: {
onMouseEnter: React.MouseEventHandler
onClick: React.MouseEventHandler
href?: string
ref?: any
} = {
ref: (el: any) => {
this.handleRef(el)
if (child && typeof child === 'object' && child.ref) {
if (typeof child.ref === 'function') child.ref(el)
else if (typeof child.ref === 'object') {
child.ref.current = el
}
}
},
onMouseEnter: (e: React.MouseEvent) => {
if (child.props && typeof child.props.onMouseEnter === 'function') {
child.props.onMouseEnter(e)
}
this.prefetch({ priority: true })
},
onClick: (e: React.MouseEvent) => {
if (child.props && typeof child.props.onClick === 'function') {
child.props.onClick(e)
}
if (!e.defaultPrevented) {
this.linkClicked(e)
}
},
}
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
// defined, we specify the current 'href', so that repetition is not needed by the user
if (props.passHref || (child.type === 'a' && !('href' in child.props))) {
childProps.href = addBasePath(as || href)
}
// If child is an <a> tag and doesn't have a href attribute, or if the 'passHref' property is
// defined, we specify the current 'href', so that repetition is not needed by the user
// Add the ending slash to the paths. So, we can serve the
// "<page>/index.html" directly.
if (process.env.__NEXT_EXPORT_TRAILING_SLASH) {
const rewriteUrlForNextExport = require('../next-server/lib/router/rewrite-url-for-export')
.rewriteUrlForNextExport
if (
this.props.passHref ||
(child.type === 'a' && !('href' in child.props))
childProps.href &&
typeof __NEXT_DATA__ !== 'undefined' &&
__NEXT_DATA__.nextExport
) {
props.href = as || href
}
// Add the ending slash to the paths. So, we can serve the
// "<page>/index.html" directly.
if (process.env.__NEXT_EXPORT_TRAILING_SLASH) {
const rewriteUrlForNextExport = require('../next-server/lib/router/rewrite-url-for-export')
.rewriteUrlForNextExport
if (
props.href &&
typeof __NEXT_DATA__ !== 'undefined' &&
__NEXT_DATA__.nextExport
) {
props.href = rewriteUrlForNextExport(props.href)
}
childProps.href = rewriteUrlForNextExport(childProps.href)
}
return React.cloneElement(child, props)
}
return React.cloneElement(child, childProps)
}
if (process.env.NODE_ENV === 'development') {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册