【发布时间】:2017-04-29 04:23:36
【问题描述】:
我正在尝试创建一个可以托管在根以外的任意路径的 React 应用程序 - "/"
所以,我正在尝试使用react-router-redux 应用自定义basename。我正在使用history 包中的createBrowserHistory 模块创建自定义browserHistory,但这似乎不会导致任何渲染。当我使用react-router 附带的browserHistory 模块时,它可以工作。
有效的示例代码:
import App from 'App'
import NoMatch from 'NoMatch'
import { Router, Route, browserHistory} from 'react-router'
import { createStore, combineReducers } from 'redux'
import { syncHistoryWithStore } from 'react-router-redux'
const store = createStore(
combineReducers({
// reducers
})
)
const history = syncHistoryWithStore(browserHistory, store)
render(
<Provider store={store}>
<Router history={history}>
<Route path="/foo" component={App}></Route>
<Route path="*" status={404} component={NoMatch}/>
</Router>
</Provider>,
document.getElementById('app')
)
当然,这不允许我动态设置basename。它总是/foo/。
这是我尝试动态设置的方法:
import App from 'App'
import NoMatch from 'NoMatch'
import { Router, Route } from 'react-router'
import { createStore, combineReducers } from 'redux'
import { syncHistoryWithStore } from 'react-router-redux'
import { createBrowserHistory } from 'history'
const store = createStore(
combineReducers({
// reducers
})
)
const browserHistory = useRouterHistory(createBrowserHistory)({
basename: window.location.pathname
});
const history = syncHistoryWithStore(browserHistory, store)
render(
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}></Route>
<Route path="*" status={404} component={NoMatch}/>
</Router>
</Provider>,
document.getElementById('app')
)
但是,当我这样做时,应用程序什么也不做。 App 组件没有被渲染——NoMatch 组件也没有被渲染——所以看起来问题不在于路由,但有些东西让Router 甚至无法启动。
有什么想法吗?
相关模块的版本:
"react": "^0.14.7"
"redux": "^3.3.1"
"react-redux": "^4.4.6"
"react-router": "^2.0.0"
"react-router-redux": "^4.0.7"
"history": "^4.4.1"
【问题讨论】:
-
v4 of
history适用于 v4 ofreact-router。您应该使用history的 v3,尽管我不能肯定这会解决您的问题。 -
是的,这就是问题所在 - 谢谢!不过,我需要使用
history的 v2。此外,在history的 v2 中,没有createBrowserHistory,只有createHistory。如果您想回答,我会将其标记为正确答案。 -
没问题。 RR v3 应该是 v2 的 API 兼容版本,它只是从 RR v1 中删除了不推荐使用的代码。不过,我不确定存在哪些历史差异导致
history的 v3 与react-router的 v2.0.0 不兼容。
标签: reactjs react-router react-redux react-router-redux