我使用react-router v4进行路由,解析查询参数,建议使用history.listen
here
我在生命周期钩子componentDidMount
中调用它来确保组件已经安装,以便我可以使用像这样的高阶组件将它作为一个组件状态提供:
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
当路线导航到新页面或新的查询参数添加到页面时,永远不会触发history.listen
。
答案 0 :(得分:2)
根据React Router V4 docs,如果您想自己管理历史记录,则需要使用<Router>
代替<BrowserRouter>
:
import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'
const history = createBrowserHistory()
<Router history={history}>
<App/>
</Router>