微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 匹配的路由不会改变路由散列更改

我正在使用react-router-dom和react-router-redux以及历史来管理我的应用程序的路由.我还使用哈希历史记录来支持旧版浏览器.以下是我的路线组件:
<Switch>
    <Route exact path={'/'} component={...} />
    <Route path={'/a'} component={...} />
    <Route path={'/b'} component={...} />
</Switch>

我的应用程序位于以下位置:http://something.com/index.html#/,并正确路由到第一个Route组件.但是,当在thunk动作创建器中使用dispatch(push(‘/ a’))尝试以编程方式切换路由时,我发现正确的路由没有匹配.

我很难调试这个……任何想法?我想它可能与我的window.location.pathname是/index.html的事实有关.

解决方法

Switch接收位置prop,或者必须用Router组件包装.您可以在 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Switch.md#children-node/找到更多信息

If a location prop is given to the,it will override the location prop on the matching child element.

所以尝试以下方法之一:

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')
);

有关路由器组件的更多信息,请访问:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Router.md

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐