匹配路由不会改变路由散列更改

时间:2018-03-01 15:57:25

标签: javascript redux react-router react-router-dom

我使用react-router-domreact-router-reduxhistory来管理我的应用的路由。我还使用哈希历史记录来支持旧版浏览器。以下是我的路线组成部分:

<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的事实有关。

1 个答案:

答案 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