我有这个分页应用程序。它正在成功运行。您可以在以下链接中看到该应用程序正在运行:https://codepen.io/PiotrBerebecki/pen/pEYPbY
class TodoApp extends React.Component {
constructor() {
super();
this.state = {
todos: ['a','b','c','d','e','f','g','h','i','j','k'],
currentPage: 1,
todosPerPage: 3
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
this.setState({
currentPage: Number(event.target.id)
});
}
render() {
const { todos, currentPage, todosPerPage } = this.state;
// Logic for displaying current todos
const indexOfLastTodo = currentPage * todosPerPage;
const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);
const renderTodos = currentTodos.map((todo, index) => {
return <li key={index}>{todo}</li>;
});
// Logic for displaying page numbers
const pageNumbers = [];
for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
pageNumbers.push(i);
}
const renderPageNumbers = pageNumbers.map(number => {
return (
<li
key={number}
id={number}
onClick={this.handleClick}
>
{number}
</li>
);
});
return (
<div>
<ul>
{renderTodos}
</ul>
<ul id="page-numbers">
{renderPageNumbers}
</ul>
</div>
);
}
}
ReactDOM.render(
<TodoApp />,
document.getElementById('app')
);
因此,我想通过放置一个新的键“元素”来将初始数组更改为关联数组,如下所示:
"todos": {
"elements":
['a','b','c','d','e','f','g','h','i','j','k']
},
更改后如何捕获这些数据?我已经尝试过这种方式:
const currentTodos = todos.map((t, index)=>{
t.elements.map((e,index)=>{
e.slice(indexOfFirstTodo, indexOfLastTodo);
})
})
它不起作用
答案 0 :(得分:1)
slice
复制数组的一部分。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
您将数组从todos
移到了todos.elements
。因此,您需要在slice
上使用todos.elements
:
const currentTodos = todos.elements.slice(indexOfFirstTodo, indexOfLastTodo);
答案 1 :(得分:0)
使用此模型,todos是不是数组的对象,而map()是数组的javascript函数。
"todos": {
"elements":
['a','b','c','d','e','f','g','h','i','j','k']
},
这将帮助您使用JavaScript skip take methods with javascript arrays
实现分页[编辑] 链接中最适合您情况的答案
var ary = [0,1,2,3,4,5,6,7];
alert(ary.splice(0,3).join(','));