Reactjs React路由器:如何在组件外部以编程方式导航?
我想导航到路径Reactjs React路由器:如何在组件外部以编程方式导航?,reactjs,react-router,Reactjs,React Router,我想导航到路径/hello,然后尝试以下操作: 从'react router'导入{browserHistory} browserHistory.push(“/hello”) 但它只将浏览器的URL更改为/hello,而没有实际导航到该页面。在组件内部,此方法起作用: this.props.history.push(“/hello”) 这是我设置路由器的方式: //为react路由器配置历史记录 const browserHistory=useRouterHistory(createBrow
/hello
,然后尝试以下操作:
从'react router'导入{browserHistory}
browserHistory.push(“/hello”)
但它只将浏览器的URL更改为/hello
,而没有实际导航到该页面。在组件内部,此方法起作用:
this.props.history.push(“/hello”)
这是我设置路由器的方式:
//为react路由器配置历史记录
const browserHistory=useRouterHistory(createBrowserHistory)({
basename:\uu basename__
})
//创建redux存储并与react router redux同步。我们已经安装了
//在src/routes/index.js中的键“router”下反应路由器redux reducer,
//因此,我们需要提供一个自定义的“selectLocationState”来通知
//对其位置进行重新定位。
const initialState=窗口的初始状态__
常量存储=配置存储(初始状态,浏览器历史)
const history=syncHistoryWithStore(浏览器历史记录、存储、{
选择LocationState:(状态)=>state.router
})
//现在我们有了Redux商店,我们可以创建路由了。我们提供
//将存储区添加到路由定义中,以便路由可以访问该定义
//钩子,比如'onEnter'。
const routes=makeRoutes(存储)
//现在已经配置了redux和react路由器,我们可以呈现
//对DOM做出反应!
ReactDOM.render(
,
document.getElementById('root'))
)
参考资料:
设置
浏览器历史记录时,我将其存储在全局命名空间中:
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: (state) => state.router
})
window.routerHistory = history
然后我可以在组件外部导航,如下所示:
window.routerHistory.push('/')