sir*_*day 7 javascript react-router redux react-router-dom
我使用react-router-dom与react-router-redux和history管理路由我的应用程序.我也使用哈希历史记录来支持旧版浏览器.以下是我的路线组件:
<Switch>
<Route exact path={'/'} component={...} />
<Route path={'/a'} component={...} />
<Route path={'/b'} component={...} />
</Switch>
Run Code Online (Sandbox Code Playgroud)
我的app位于以下位置:http://something.com/index.html#/并正确路由到第一个Route组件.但是,当dispatch(push('/a'))在thunk动作创建器中使用以尝试以编程方式切换路由时,我发现正确的路由没有匹配.
我很难调试这个......任何想法?我想这也许是与事实,我做的window.location.pathname是/index.html.
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);Run Code Online (Sandbox Code Playgroud)
或者,您可以采用另一种方式,将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')
);Run Code Online (Sandbox Code Playgroud)
有关Router组件的更多信息,请访问:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Router.md
| 归档时间: |
|
| 查看次数: |
441 次 |
| 最近记录: |