history.listen 未在 componentDidMount 中触发

history.listen not triggered in componentDidMount

我正在使用 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

根据 React Router V4 docs,如果您想自己管理历史记录,您需要使用 <Router> 而不是 <BrowserRouter>:

import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>