我使用react-router-dom
与react-router-redux
和history
来管理我的应用的路由。我还使用哈希历史记录来支持旧版浏览器。以下是我的路线组成部分:
<Switch>
<Route exact path={'/'} component={...} />
<Route path={'/a'} component={...} />
<Route path={'/b'} component={...} />
</Switch>
我的应用程序位于http://something.com/index.html#/
位置,并正确路由到第一个Route
组件。但是,当在thunk action creator中使用dispatch(push('/a'))
尝试以编程方式切换路由时,我发现正确的路由没有匹配。
我很难调试这个......任何想法?我认为这可能与我window.location.pathname
为/index.html
的事实有关。
答案 0 :(得分:5)
Switch
接收位置道具,或者必须使用路由器组件包装。您可以在https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md#children-node/
如果给了一个位置道具,它将覆盖匹配的子元素上的位置道具。
请尝试以下方法之一:
class Example extends Component {
render() {
return (
<Switch location={this.props.location}>
<Route exact path={'/'} component={...} />
<Route path={'/a'} component={...} />
<Route path={'/b'} component={...} />
</Switch>
);
}
// location is react-router-redux reducer
export default connect(state => ({location: state.location}))(Example);
或者,您可以采用另一种方式,将Switch组件与路由器组件包装在一起(我从我的一个项目中粘贴了代码):
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { Route, Switch } from 'react-router-dom';
import { ConnectedRouter } from 'react-router-redux';
import createHistory from 'history/createBrowserHistory';
import configureStore from './store/configureStore';
const history = createHistory();
const store = configureStore(history);
// We wrap Switch component with ConnectedRouter:
ReactDOM.render(
<Provider store={store}>
<ConnectedRouter history={history}>
<Switch>
<Route exact path={'/'} component={...} />
<Route path={'/a'} component={...} />
<Route path={'/b'} component={...} />
</Switch>
</ConnectedRouter>
</Provider>,
document.getElementById('root')
);
有关Router
组件的更多信息,请访问:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Router.md