【发布时间】:2017-04-19 20:05:10
【问题描述】:
我使用react-router v4进行路由,解析查询参数,推荐使用history.listenhere
我在生命周期钩子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。
【问题讨论】:
-
您是否在整个项目中使用同一个导出的
history实例?即你用它来渲染<Router history={history}>? -
您能否提供一个更完整的代码示例,展示您在何处使用 React Router V4 组件?
-
我也遇到了
listen()未触发的问题。我有这样的历史记录分配给我的路由器历史记录:<Router history={history}>,我希望listen()在路由更改时触发,但它永远不会触发。 -
@PaulS 是的,但是我必须提到我正在使用
import BrowserRouter as Router from react-router-dom。 -
您需要使用
<Router>,而不是<BrowserRouter>。<BrowserRouter>创建自己的history实例。
标签: javascript reactjs react-router react-router-v4