我需要用于分页页面的唯一网址。
当我点击分页的页数 - 网址被更改,如 ... / album / 1 / page /(选择的页数) - 并且没关系,但是当我尝试复制我的网址并将其粘贴为(... / album / 1 / page / 2),我的应用仍会加载第一页。
我需要有机会从网址加载任何网页。
这是我此刻的路线:
<Route path="album/:id" component={AlbumsShow}>
<Route path="page/:newPage" component={AlbumsShow} />
</Route>
这是组件:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import Pager from 'react-pager';
import {browserHistory} from 'react-router';
class AlbumsShow extends Component {
constructor(props) {
super(props);
this.renderImage = this.renderImage.bind(this);
this.handlePageChanged = this.handlePageChanged.bind(this);
this.state = {
total: 3,
current: 0,
visiblePage: 2,
};
}
handlePageChanged(newPage) {
this.setState({ current : newPage });
browserHistory.push({
pathname: (newPage+1),
});
}
renderImage() {
const imgs = this.props.images.length > 10 ?
this.props.images.slice(this.state.current * 10, (this.state.current + 1) * 10) :
this.props.images;
return imgs.map((image, page) => (
<li className="image_list" key={image.id}>
<img className="image_list_img" alt="item" src={image.img} />
</li>
));
}
render() {
return (
<div className="wrapper">
<ul>
{this.renderImage()}
</ul>
{this.props.images.length > 10 ?
<Pager
total={this.state.total}
current={this.state.current}
visiblePages={this.state.visiblePage}
titles={{ first: 'First page', last: 'Last page' }}
onPageChanged={this.handlePageChanged}
/> : null
}
</div>
);
}
}
function mapStateToProps(state, ownProps) {
const currentAlbumId = parseInt(ownProps.params.id, 10);
return {
images: state.main.albums.filter(album => album.id === currentAlbumId)[0].images,
};
}
export default connect(mapStateToProps)(AlbumsShow);
答案 0 :(得分:2)
请使用路由道具中的页码,即:newPage
,并将其mapStateToProps
映射为pageNumber
(可选)。
function mapStateToProps(state, ownProps) {
const currentAlbumId = parseInt(ownProps.params.id, 10);
const pageNumber = parseInt(ownProps.params.newPage, 10);
return {
pageNumber,
images: state.main.albums.filter(album => album.id === currentAlbumId)[0].images,
};
}
然后,不要将页码存储在组件的状态中,而是将其作为道具使用。
<Pager current={this.props.pageNumber} ... />
处理过渡到下一页时,只需通知您的路由器,不要自行存储状态。您的组件将使用新的pageNumber值重新呈现。
handlePageChanged(newPage) {
const { id } = this.props.params
const { pageNumber } = this.props
const target = `/albums/${id}/page/${pageNumber + 1}`
browserHistory.push({
pathname: target,
});
}
一直向下,将this.state.current
的出现次数更改为this.props.pageNumber
,您就可以了。
现在,网址变为single source of truth。
注意:您可以更改路由参数以更好地匹配其含义:
<Route path="album/:albumId" component={AlbumsShow}>
<Route path="page/:pageIndex" component={AlbumsShow} />
</Route>
之后,您只需使用这些ID而不进行映射:
const { albumId, pageIndex } = this.props.params
答案 1 :(得分:1)
您可以检查page
内的componentWillReceiveProps
参数,并将其设置为current
状态,然后更新Pager
组件。
componentWillReceiveProps(newProps) {
const { newPage } = newProps.params;
if (newPage !== this.state.current) {
this.setState({ current: page });
}
}