gpt4 book ai didi

javascript - 第二次点击后即可分页

转载 作者:行者123 更新时间:2023-12-02 14:21:34 25 4
gpt4 key购买 nike

这是我的 jsFiddle 示例:https://jsfiddle.net/0se06am5/

class Pagination extends React.Component {
constructor(props) {
super(props);

this.state = { current: 1 };
this.items = ['a', 'b', 'c'];
this.filteredItems = [];

this.prev = this.prev.bind(this);
this.next = this.next.bind(this);
this.set = this.set.bind(this);
this.filter = this.filter.bind(this);
}

componentWillUpdate() {
this.filter();
}

prev() {
this.setState({ current: this.state.current - 1});
}

next() {
this.setState({ current: this.state.current + 1});
}

set(val) {
this.setState({ current: val });
}

filter() {
this.filteredItems = this.items.filter((i, idx) => {
return (idx + 1) === this.state.current;
})
}

render() {
return (
<div>
{this.filteredItems.map((i, idx) => {
return <span key={`item_${idx}`}>{i}</span>;
})}<br />

<span onClick={this.prev}>prev</span>

<span onClick={this.set.bind(this, 1)}>1</span>
<span onClick={this.set.bind(this, 2)}>2</span>
<span onClick={this.set.bind(this, 3)}>3</span>

<span onClick={this.next}>next</span>

<br /><span>current: {this.state.current}</span>
</div>
)
}
}

当您单击分页项目时,您发现它无法正常工作。

为什么 filter() 方法运行得很晚?我应该在哪里而不是 componentWillUpdate() 我应该移动这个方法或者我应该写什么不同的?

最佳答案

componentWillUpdate在初始渲染中执行。将过滤移至渲染,因为它不会更改状态本身,并且它应该在渲染组件时运行( demo ):

render()
{
const items = this.items.filter((i, idx) => {
return (idx + 1) === this.state.current;
}).map((i, idx) => {
return <span key={`item_${idx}`}>{i}</span>;
});
return (
<div>

{items}

<br />

<span onClick={this.prev}>prev</span>

<span onClick={this.set.bind(this, 1)}>1</span>
<span onClick={this.set.bind(this, 2)}>2</span>
<span onClick={this.set.bind(this, 3)}>3</span>

<span onClick={this.next}>next</span>

<br /><span>current: {this.state.current}</span>
</div>
)
}

您还可以将 .filter.map 调用合并为一个 .reduce 调用 ( demo ):

const items = this.items.reduce((arr, i, idx) => {
if((idx + 1) === this.state.current) {
arr.push(
<span key={`item_${idx}`}>{i}</span>
);
}

return arr;
}, []);

关于javascript - 第二次点击后即可分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38621839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com