首页 > 解决方案 > 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 个项目(卡片)。我想要做的是当你点击另一个页面时,我希望它重新渲染并在屏幕上显示其他卡片。

那么,我怎样才能做到这一点呢?如何将状态设置为您单击的页面,以便将正确的卡片呈现到屏幕上?

在此先感谢您的帮助。希望这是有道理的。

标签: reactjs

解决方案


更新:除了下面的 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在. 如果您一次获取所有数据,您可以这样做并存储在状态中。awaitthencomponentDidMount


推荐阅读