I am using react-router v4 for routing, to parse query params, it has been recommended to use history.listen
here
I am calling it within the lifecycle hook componentDidMount
to ensure that the component has mounted so that I can provide it as a piece of component state using a Higher Order Component like this:
import createHistory from 'history/createBrowserHistory';
import qs from 'qs';
import { compose, lifecycle, withState } from 'recompose';
export const history = createHistory();
const withQs = compose(
withState('search', 'setSearch', {}),
lifecycle({
componentDidMount: function () {
// works on the client side
history.listen(() => {
// history.location = Object.assign(history.location,
// parse the search string using your package of choice
// { query: parseQueryString(history.location.search) }
// )
console.log('History Location', history.location);
console.log('Search', history.location.search);
})
}
})
)
export default withQs
The history.listen
is never triggered when a route navigates to the new page or a new query param is added to the page.
Per the React Router V4 docs , if you want to manage history yourself, you need to use <Router>
instead of <BrowserRouter>
:
import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()
<Router history={history}>
<App/>
</Router>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.