Improve route prefetch docs: add client side imperative code (#4213)

I stumbled into this Issue https://github.com/zeit/next.js/issues/2868 and thought it should be mentioned properly in the documentation.
This commit is contained in:
Robin Wieruch 2018-05-25 20:26:45 +08:00 committed by Tim Neutkens
parent 8c6a4ebb1d
commit 2c3e8d3201

View file

@ -720,6 +720,29 @@ export default ({ url }) =>
</div> </div>
``` ```
The router instance should be only used inside the client side of your app though. In order to prevent any error regarding this subject, when rendering the Router on the server side, use the imperatively prefetch method in the `componentDidMount()` lifecycle method.
```jsx
import React from 'react'
import Router from 'next/router'
export default class MyLink extends React.Component {
componentDidMount() {
Router.prefetch('/dynamic')
}
render() {
return (
<div>
<a onClick={() => setTimeout(() => url.pushTo('/dynamic'), 100)}>
A route transition will happen after 100ms
</a>
</div>
)
}
}
```
### Custom server and routing ### Custom server and routing
<p><details> <p><details>