我正在尝试创建一个可以在根目录以外的任意路径托管的React应用程序 - "/"
所以,我正在尝试使用basename
应用自定义react-router-redux
。我正在使用browserHistory
包中的createBrowserHistory
模块创建自定义history
,但这似乎导致无法呈现任何内容。当我使用browserHistory
附带的react-router
模块时,它可以正常工作。
有效的示例代码:
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"
答案 0 :(得分:1)
history
的第4版适用于react-router
的第4版,并且有一些重要的API更改,使其与先前版本的react-router
不兼容。 history
的v2 / 3应与react-router
的v2 / 3一起使用。
答案 1 :(得分:0)
import React from 'react';
import ReactDOM from 'react-dom';
import Root from 'src/Root/Root';
import configureStore from 'src/store/configureStore'
// import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux'
import { createHistory, useBasename } from 'history'
let browserHistory = useBasename(createHistory)({
basename: '/base'
})
const store = configureStore()
const history = syncHistoryWithStore(browserHistory, store)
ReactDOM.render( <Root store={store} history={history} />, document.getElementById('appRoot'));
此代码可以正常使用
"dependencies": {
"antd": "^2.5.2",
"console-polyfill": "^0.2.3",
"es5-shim": "^4.5.9",
"es6-promise": "^4.0.5",
"file-loader": "^0.9.0",
"history": "3.2.1",
"immutable": "^3.8.1",
"react": "^15.4.1",
"react-constants": "^0.2.2",
"react-dom": "^15.4.1",
"react-image-gallery": "^0.7.4",
"react-redux": "^5.0.0",
"react-router": "^3.0.0",
"react-router-redux": "^4.0.7",
"redux": "^3.6.0",
"redux-immutablejs": "^0.0.8",
"redux-thunk": "^2.1.0",
"whatwg-fetch": "0.11.1"
}