我的应用程序中有这样的路由设置:
DataController
我的应用程序组件如下所示:
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="/books" component={Main} url='/polls/getbooks/'/>
<Route path="/books/bookdetail" component={BookDetail} />
</Route>
</Router>
这是我的主要内容:
class App extends React.Component {
pageContent() {
let content = <Spinner/>;
if (!this.props.dataLoading) {
content = (
<ReactCSSTransitionGroup
component="div"
transitionName="bobon-transition"
transitionEnterTimeout={500}
transitionLeaveTimeout={500}
transitionAppear={true}
>
{ React.cloneElement(this.props.children, {
key: this.props.location.pathname
}) }
</ReactCSSTransitionGroup>
);
}
return content;
}
render() {
let content = null;
if (!this.state.authed) {
content = (
<div className="pf-authed">
<AppHeader/>
<div className="bobon-page-content page-content">
{ this.pageContent() }
</div>
<AppFooter/>
</div>
);} else {
content = (
<div className="pf-authed">
<AppHeaderAuthed/>
<div className="bobon-page-content page-content">
{ this.pageContent() }
</div>
<AppFooter/>
</div>
);
}
}
当用户登录时,页面呈现正确并且他看到了“BookList”#39;零件。但是在Booklist中,我导航到了BookDetailView&#39;当用户选择书籍时,使用browserHistory.push(&#39; / books / bookdetail&#39;)。问题在于书籍详细信息视图中的书籍列表&#39;组件停留在页面上,页面如下所示:
class Main extends React.component {
render() {
if(!this.state.loaded) {
return <Spinner/>
}
if(this.state.authed) {
content = (
<div >
<BookList apiData = {this.state.childData}/>
</div>
);
} else {
content = (
<div>
<LoginForm/>
</div>
);
}
return content;
}
}
如果我要输入我的浏览器/ books / bookdetail,那么视图将正确呈现为
<BookDetail>
<BookList>
为什么&#39; BookList&#39;当我使用browserHistory.push()页面时,在bookdetail上呈现?
非常感谢。
答案 0 :(得分:1)
在以前版本的React Router(版本2.0.0)中,我们曾经:
import { browserHistory } from './react-router'
// then in your component
browserHistory.push('/books/bookdetail')
在较新版本的React Router(版本2.4.0)中,我们可以使用this.props.router.push('/books/bookdetail')
。为此,您需要使用 withRouter
包装器。例如,在导出BookList
组件时可以这样做。
import { withRouter } from 'react-router';
class BookList extends React.Component {
clickHandler() {
this.props.router.push('/books/bookdetail');
}
render() {
// if used in the render method you can use:
// <h1 onClick={()=>this.props.router.push('/books/bookdetail')}>Book title</h1>
}
}
export default withRouter(BookList);
更多信息:
https://github.com/ReactTraining/react-router/blob/master/docs/API.md#withroutercomponent-options
react - router withRouter does not inject router