javascript - history.listen 未在 componentDidMount 中触发

标签 javascript reactjs react-router react-router-v4

我正在使用 react-router v4 进行路由,解析查询参数,建议使用 history.listen here

我在生命周期 Hook 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>

关于javascript - history.listen 未在 componentDidMount 中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43505124/

相关文章:

javascript - 如何根据 Marionette.CompositeView 中的集合更改项目 View 容器值

javascript - 为什么数据没有显示在react-bootstrap-table中?

reactjs - 如何在material ui SVG ICON中使用自定义SVG文件

reactjs - React 不路由到 "/"以外的路由

javascript - 组件函数运行多次react

javascript - 如何使用授权 token 向 api 发出 http 请求?

javascript - LESS 属性在 Firefox 中加载不一致

javascript - 如何在 JavaScript 循环中提醒一次

javascript - 输入 onChange 无法使用引用值

javascript - 使用 React-Router-Config 设置页面标题