我正在尝试更新在div中听到的元素。
我得到了一个对象数组
const elements = [
{
title: '0',
url: 'url',
description: 'description',
published: '2020-10-10',
updated: '2020-10-10',
afected: {
title: 'afected',
url: 'afected'
}
},
{
title: '1',
url: 'url',
description: 'description',
published: '2020-10-10',
updated: '2020-10-10',
afected: {
title: 'afected',
url: 'afected'
}
},
{
title: '2',
url: 'url',
description: 'description',
published: '2020-10-10',
updated: '2020-10-10',
afected: {
title: 'afected',
url: 'afected'
}
},
{
title: '3',
url: 'url',
description: 'description',
published: '2020-10-10',
updated: '2020-10-10',
afected: {
title: 'afected',
url: 'afected'
}
}
];在我有了创建分页的变量和方法之后
const rowsPerPage = 2;
let init = 0;
let end = rowsPerPage -1;
const pages = Math.ceil(elements.length / rowsPerPage);
let rowsToShow = [];
let paginate = (page) => {
end = (page * rowsPerPage);
end = end >= elements.length ? elements.length : end;
init = (page * rowsPerPage) - rowsPerPage ;
rowsToShow = elements.slice(init, end);
}
paginate(1);然后我用元素渲染div
return <Wrapper>
<div className='container'>
<div className='elements'>
{ elements && <div>
{ rowsToShow.map((item, index) => <TextCardLayoutComponent
key={ index }
title={ item.title }
url={ item.url }
description={ item.description }
published={ item.published }
updated={ item.updated }
afectedTitle={ item.afected.title }
afectedUrl={ item.afected.url } /> )
}
</div>
}
{_.times(pages, (i) => {
return <a onClick={ () => paginate( i+1 ) }> { i+1 } </a>
})}
</div>
</div>
</Wrapper>
}
export default LayoutComponent;因此,当函数分页被称为将视图中的元素更新为变量rowsToShow时,现在我已经在'rowsToShow‘中显示了新的元素数组,但是我需要用这个数组更新视图。
发布于 2020-06-26 07:00:54
你需要在状态下存储你想要渲染的东西。然后,您可以操作该状态,以显示尽可能多或尽可能少的每一页。像这样的东西应该可以工作,这样您就可以适应您的代码。
const LayoutComponent = () => {
const [data, setData] = useState(elements) // I'm initialising state with your elements array
const [pagination, setPagination] = useState({start: 0, end: 0}) // this state here is to define what we should show on the pages
return (
<div>
// here you can slice the data array to show how many elements should show
{data.slice(pagination.start, pagination.end).map((element) => {
<div>
{element.title}
{element.description}
// obviously you can render here as much as you like
</div>
})
<div>
// here we can set pagination state to then render different elements in the state
<div onClick={() => setPagination({start: 0, end: 2})}> Page 1 </div>
<div onClick={() => setPagination({start: 2, end: 4})}> Page 2 </div>
</div>
</div>
)
}这是一种伪代码,您可能需要调整一下,但如果有帮助,请告诉我!
https://stackoverflow.com/questions/62589452
复制相似问题