0

Here is my jsFiddle example: 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>
        )
    }
}

When you click on pagination items, then you realized that it not working correctly.

Why filter() method runs to late? Where instead of componentWillUpdate() i should move this method or what should i write different?

mwl
  • 1,448
  • 14
  • 18

1 Answers1

2

componentWillUpdate is not executed in the initial render. Move the filtering to render as it doesn't change the state itself, and it should run whenever the component is rendered (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>
    )
}

You can also combine the .filter and the .map calls into one .reduce call (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;
}, []);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209