这是我的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()
我应该移动这个方法或者我应该写什么不同?
答案 0 :(得分:2)
componentWillUpdate
在初始渲染中执行 。
将过滤移动到渲染,因为它不会更改状态本身,并且它应该在组件呈现时运行(demo):
options
{
backtrack=true;
memoize=true;
}
您还可以将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
来电(demo):
.reduce