我正在尝试使用react路由器v4。我有一个应用程序,我有两个页面:登录页面和应用程序页面。在我的应用页面中,我有三个部分:标题,侧边栏和内容部分。这就是我想要的
这就是我现在设置路线的方式
class Root extends Component {
render() {
return (
<div>
<main>
<Route exact path="/" component={LoginPage} />
<Route exact path="/app" component={App}>
</Route>
</main>
</div>
);
}
}
和App.js
class App extends Component {
render() {
return (
<div>
<Header/>
<Sidebar/>
<main>
<Switch>
<Route exact path="/trivia" component={TriviaPanel}/>
<Route exact path="/image" component={ImagePanel}/>
</Switch>
</main>
</div>
);
}
}
MenuPanel.js(从中我去琐事和图像)
import React, { Component } from 'react';
import { push } from 'react-router-redux'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
const styles = require('./sidebar.css');
class MenuPanel extends Component {
render() {
return (
<div>
<div className="navbar-side">
<div className="tessact-logo"></div>
<div className="navbar-item active" onClick={() => this.props.toTriviaPage()}>
<a className="navbar-item-link"><span className="fa fa-comment"></span> TRIVIA</a>
</div>
<div className="navbar-item" onClick={() => this.props.toImagePage()}>
<a className="navbar-item-link"><span className="fa fa-picture-o"></span> IMAGES</a>
<div className="navbar-item-inside">
<a className="navbar-item-inside-link">PERSONSS</a>
<a className="navbar-item-inside-link">BRANDS</a>
<a className="navbar-item-inside-link">OBJECTS</a>
</div>
</div>
<div className="navbar-item">
<a className="navbar-item-link"><span className="fa fa-tags"></span> KEYWORDS</a>
</div>
</div>
</div>
);
}
}
const mapDispatchToProps = dispatch => bindActionCreators({
toTriviaPage: () => push('/app/trivia'),
toImagePage: () => push('/app/image')
}, dispatch)
export default connect(
null,
mapDispatchToProps
)(MenuPanel)
我希望TriviaPanel在登陆App时成为默认视图。目前我登陆登录页面,当我点击登录时,App页面无法正常工作。我看不到侧边栏和标题之外的任何内容,当我点击侧边栏中的内容时,它也会消失(琐事链接)。
我应该如何实现这一目标?在react router v3中有一个很好的childroutes选项。我该怎么做才能解决这个问题?
答案 0 :(得分:1)
问题出在App
。您正在正确进行嵌套,但您的路径是错误的。查看Root
App
组件位于/app
。因此,您的嵌套路由还应在其路径中包含/app
前缀:
class App extends Component {
render() {
return (
<div>
<Header/>
<Sidebar/>
<main>
<Switch>
<Route exact path="/app/trivia" component={TriviaPanel}/>
<Route exact path="/app/image" component={ImagePanel}/>
{/* Catch-all route for TriviaPanel */}
<Route component={TriviaPanel}/>
</Switch>
</main>
</div>
);
}
}
<强>更新强>
啊,显然这是react-router-redux的一个已知问题:https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/redux.md#blocked-updates
您需要使用withRouter
中的react-router-dom
HOC包装已连接的组件:
// before
export default connect(
null,
mapDispatchToProps
)(MenuPanel)
// after
import { withRouter } from 'react-router-dom'
export default withRouter(connect(
null,
mapDispatchToProps
)(MenuPanel))