Reactjs 如何使用历史记录使用react router更新分页栏?
以下是我的路线:Reactjs 如何使用历史记录使用react router更新分页栏?,reactjs,react-router,Reactjs,React Router,以下是我的路线: <BrowserRouter> <Switch> <Route exact path="/" component={Home} /> <Route exact path="/pages" component={Pages} /> <Route path="/page/:page(\d+)" component={Pages} /> </Switch> </Browser
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/pages" component={Pages} />
<Route path="/page/:page(\d+)" component={Pages} />
</Switch>
</BrowserRouter>
这是我遇到问题的组件:
class Pages extends React.Component {
buildHref = href => `/page/${href}`;
componentDidMount() {
this.props.history.push(this.props.match.url);
}
handlePageChange = page => {
this.props.history.push(`/page/${page.selected + 1}`);
};
render() {
return (
<div>
<ReactPaginate
previousLabel="<"
nextLabel=">"
pageCount={10}
pageRangeDisplayed={10}
onPageChange={this.handlePageChange}
initialPage={parseInt(this.props.match.params.page - 1, 0)}
containerClassName={"pagination"}
activeClassName={"active"}
hrefBuilder={this.buildHref}
/>
</div>
);
}
}
export default withRouter(Pages);
类页面扩展React.Component{
buildHref=href=>`/page/${href}`;
componentDidMount(){
this.props.history.push(this.props.match.url);
}
handlePageChange=页面=>{
this.props.history.push(`/page/${page.selected+1}`);
};
render(){
返回(
);
}
}
使用路由器导出默认值(页);
代码:
当我使用浏览器的历史记录返回时,url会更新,但分页栏不会更改。活动类保留在同一元素上。在这种情况下,用正确的活动页码重新输入分页栏的最佳方式是什么
同时返回时,它将在某一点显示/page/NaN,之后将无法继续前进。为什么要从初始页面选择中减去1:
initialPage={parseInt(this.props.match.params.page-1,0)}
您希望分页组件显示与url相同的编号
因此initialPage={parseInt(this.props.match.params.page,0)}
应该可以正常工作
此外,为什么:
componentDidMount() {
this.props.history.push(this.props.match.url);
}
你不应该需要它,它可能会干扰你的分页更新-1是因为如果url中有一个/page/6,我重新加载页面,它会使页面7处于活动状态。如果没有componentDidMount,我根本无法访问/page,它将重定向到/page/NaN