reactjs - React-当我点击不同的页面时如何改变状态?
问题描述
在我的程序中,我在屏幕上放置了各种卡片,上面有角色的图片和有关该角色的信息。我从 API 中提取所有这些信息,并负责进行客户端分页以一次仅在屏幕上显示几张卡片。
这是我的代码:
genCard = () => {
const { isLoaded, items, currentPage, totalNumberPages, recordsPerPage } = this.state;
if (isLoaded) {
let returnCard = [];
let i;
for(i = currentPage; i < recordsPerPage; i++) {
returnCard.push(<Card key={items[i].id} cardName={items[i].name} imgSrc={items[i].image} birthYear={items[i].birth_year}/>);
}
return returnCard;
}
return null;
};
handlePageClick = (data) => {
let selected = data.selected;
let offset = Math.ceil(selected * this.props.perPage);
this.setState({
})
};
如您所见,我使用 for 循环在屏幕上一次仅显示 10 个项目(卡片)。我想要做的是当你点击另一个页面时,我希望它重新渲染并在屏幕上显示其他卡片。
那么,我怎样才能做到这一点呢?如何将状态设置为您单击的页面,以便将正确的卡片呈现到屏幕上?
在此先感谢您的帮助。希望这是有道理的。
解决方案
更新:除了下面的 JSFiddle 链接之外,还在这里添加代码片段。
function Card(props) {
return <div>I'm card {props.id}</div>
}
class Cards extends React.Component {
constructor(props) {
super(props)
this.state = {
isLoaded: false,
items: [1,2,3,4,5,6,7,8,9,10, 11, 12, 13, 14, 15],
currentPage: 1,
recordsPerPage: 5,
itemStartIndexOnPage: 0,
tempCount: 0
}
}
getCards = () => {
const {items, itemStartIndexOnPage, recordsPerPage} = this.state;
const itemsForThisPage = items.slice(itemStartIndexOnPage, itemStartIndexOnPage + recordsPerPage);
let cards = itemsForThisPage.map((item, i) => <Card key={item} id={item} {...item} />)
return cards;
}
handlePageClick = (data) => {
let selected = data;
let offset = Math.ceil((selected - 1) * this.state.recordsPerPage);
this.setState({
currentPage: selected,
itemStartIndexOnPage: offset
})
}
render() {
return (
<div>
Page No: {this.state.currentPage}
{this.getCards()}
<button onClick={() => this.handlePageClick(1)}>Page 1</button>
<button onClick={() => this.handlePageClick(2)}>Page 2</button>
<button onClick={() => this.handlePageClick(3)}>Page 3</button>
</div>
)
}
}
ReactDOM.render(<Cards />, document.querySelector("#app"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"></div>
如果这就是你要找的,我已经写了这个片段。
setState
重新渲染组件树。所以调用handlePageClick
点击分页按钮,你可以调用更新组件中卡片的函数getCards()
。render()
如果您需要在页面单击时从 API 端点获取项目子集,您可以进行handlePageClick
异步并setState
在. 如果您一次获取所有数据,您可以这样做并存储在状态中。await
then
componentDidMount
推荐阅读
- arrays - Volley Json 解析
- cuda - cudaMemPrefetchAsync 上的设备序号无效
- javascript - 错误:3 INVALID_ARGUMENT:名称“Hello”与模式 DialogFlow 不匹配
- ios - 为什么在Auth0的Lock上使用数据库连接登录时没有附加参数
- php - php数据表:无效的json响应
- hyperledger-fabric - 如何使 Hyper ledger Composer 查询不区分大小写?
- java - java.lang.ClassNotFoundException: afu.com.sun.source.tree.Tree$Kind
- sql - 用字符替换 SQL 结果
- javascript - Javascript/Jquery 通过事件切换对象
- redirect - CakePhp 无法重定向 beforeFilter