【问题标题】:React Router: how to navigate programatically outside of a component?React Router:如何在组件之外以编程方式导航?
【发布时间】:2016-08-10 12:05:05
【问题描述】:

我想导航到路径 /hello 并尝试以下操作:

import { browserHistory } from 'react-router'
browserHistory.push('/hello')

但它只会将浏览器的 URL 更改为 /hello,而不会真正导航到该页面。在组件内部,此方法有效:

this.props.history.push('/hello')

这就是我设置路由器的方式:

// Configure history for react-router
const browserHistory = useRouterHistory(createBrowserHistory)({
  basename: __BASENAME__
})

// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the key "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.__INITIAL_STATE__
const store = configureStore(initialState, browserHistory)
const history = syncHistoryWithStore(browserHistory, store, {
  selectLocationState: (state) => state.router
})

// Now that we have the Redux store, we can create our routes. We provide
// the store to the route definitions so that routes have access to it for
// hooks such as `onEnter`.
const routes = makeRoutes(store)

// Now that redux and react-router have been configured, we can render the
// React application to the DOM!
ReactDOM.render(
  <Root history={history} routes={routes} store={store} />,
  document.getElementById('root')
)

参考资料:

  1. https://github.com/reactjs/react-router/blob/master/upgrade-guides/v2.0.0.md#programmatic-navigation
  2. https://github.com/reactjs/react-router/issues/1081

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    当我设置 browserHistory 时,我将它存储在一个全局命名空间中:

    const history = syncHistoryWithStore(browserHistory, store, {
      selectLocationState: (state) => state.router
    })
    window.routerHistory = history
    

    然后我可以在如下组件之外导航:

    window.routerHistory.push('/')
    

    【讨论】:

      猜你喜欢
      • 2017-10-23
      • 2018-03-25
      • 2018-04-04
      • 2017-07-31
      • 1970-01-01
      相关资源
      最近更新 更多