diff --git a/examples/with-shallow-routing/pages/index.js b/examples/with-shallow-routing/pages/index.js index fd9a55676b..019d46b053 100644 --- a/examples/with-shallow-routing/pages/index.js +++ b/examples/with-shallow-routing/pages/index.js @@ -1,11 +1,11 @@ import React from 'react' import Link from 'next/link' -import Router from 'next/router' +import Router, { withRouter } from 'next/router' import { format } from 'url' let counter = 1 -export default class Index extends React.Component { +class Index extends React.Component { static getInitialProps ({ res }) { if (res) { return { initialPropsCounter: 1 } @@ -23,24 +23,35 @@ export default class Index extends React.Component { } incrementStateCounter () { - const { url } = this.props - const currentCounter = url.query.counter ? parseInt(url.query.counter) : 0 + const { router } = this.props + const currentCounter = router.query.counter + ? parseInt(router.query.counter) + : 0 const href = `/?counter=${currentCounter + 1}` Router.push(href, href, { shallow: true }) } render () { - const { initialPropsCounter, url } = this.props + const { initialPropsCounter, router } = this.props return (

This is the Home Page

- About + + About + - +

"getInitialProps" ran for "{initialPropsCounter}" times.

-

Counter: "{url.query.counter || 0}".

+

+ Counter: "{router.query.counter || 0} + ". +

) } } + +export default withRouter(Index) diff --git a/readme.md b/readme.md index a431868a52..3ad5ca3486 100644 --- a/readme.md +++ b/readme.md @@ -600,14 +600,17 @@ const as = href Router.push(href, as, { shallow: true }) ``` -Now, the URL is updated to `/?counter=10`. You can see the updated URL with `this.props.url` inside the `Component`. +Now, the URL is updated to `/?counter=10`. You can see the updated URL with `this.props.router.query` inside the `Component` (make sure you are using [`withRouter`](#using-a-higher-order-component) around your `Component` to inject the `router` prop). -You can watch for URL changes via [`componentWillReceiveProps`](https://facebook.github.io/react/docs/react-component.html#componentwillreceiveprops) hook as shown below: +You can watch for URL changes via [`componentDidUpdate`](https://reactjs.org/docs/react-component.html#componentdidupdate) hook as shown below: ```js -componentWillReceiveProps(nextProps) { - const { pathname, query } = nextProps.url - // fetch data based on the new query +componentDidUpdate(prevProps) { + const { pathname, query } = this.props.router + // verify props have changed to avoid an infinite loop + if (query.id !== prevProps.router.query.id) { + // fetch data based on the new query + } } ```