From 7637e8d031bc1d18674f71f4b65ea54f37ae784d Mon Sep 17 00:00:00 2001 From: Drew McMillan Date: Mon, 9 Mar 2020 16:27:36 +0000 Subject: [PATCH] Make initial location POP optional --- FAQ.md | 12 ++++++++++++ index.d.ts | 1 + src/ConnectedRouter.js | 12 ++++++++---- test/ConnectedRouter.test.js | 12 ++++++++++++ 4 files changed, 33 insertions(+), 4 deletions(-) diff --git a/FAQ.md b/FAQ.md index 772f63c0..3d635980 100644 --- a/FAQ.md +++ b/FAQ.md @@ -353,3 +353,15 @@ ReactDOM.render( ) ``` + +### How to stop initial location change +In order to make this package more compatible with react-router-redux, a LOCATION_CHANGE action is dispatched for the initial location. This can however be disabled via the `noInitialPop` prop. +```js +ReactDOM.render( + + + + + +) +``` diff --git a/index.d.ts b/index.d.ts index c56beb15..79c82bf7 100644 --- a/index.d.ts +++ b/index.d.ts @@ -17,6 +17,7 @@ declare module 'connected-react-router' { interface ConnectedRouterProps { history: History; context?: React.Context; + noInitialPop?: boolean; } export type RouterActionType = Action; diff --git a/src/ConnectedRouter.js b/src/ConnectedRouter.js index bbf097c6..58d1426b 100644 --- a/src/ConnectedRouter.js +++ b/src/ConnectedRouter.js @@ -69,10 +69,13 @@ const createConnectedRouter = (structure) => { // Listen to history changes this.unlisten = history.listen(handleLocationChange) - // Dispatch a location change action for the initial location. - // This makes it backward-compatible with react-router-redux. - // But, we add `isFirstRendering` to `true` to prevent double-rendering. - handleLocationChange(history.location, history.action, true) + + if (!props.noInitialPop) { + // Dispatch a location change action for the initial location. + // This makes it backward-compatible with react-router-redux. + // But, we add `isFirstRendering` to `true` to prevent double-rendering. + handleLocationChange(history.location, history.action, true) + } } componentWillUnmount() { @@ -105,6 +108,7 @@ const createConnectedRouter = (structure) => { basename: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.func, PropTypes.node ]), onLocationChanged: PropTypes.func.isRequired, + noInitialPop: PropTypes.bool, } const mapDispatchToProps = dispatch => ({ diff --git a/test/ConnectedRouter.test.js b/test/ConnectedRouter.test.js index cdd4f65c..9c15ccd5 100644 --- a/test/ConnectedRouter.test.js +++ b/test/ConnectedRouter.test.js @@ -191,6 +191,18 @@ describe('ConnectedRouter', () => { history.push('/new-location') expect(renderCount).toBe(2) }) + + it('does not call `props.onLocationChanged()` on intial location when `noInitialPop` prop is passed ', () => { + mount( + + +
Home
} /> +
+
+ ) + + expect(onLocationChangedSpy.mock.calls).toHaveLength(0) + }) }) describe('with immutable structure', () => {