2016-07-27 173 views
0

這是我的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

什麼是不工作? –

+0

您必須在分頁上點擊兩次以獲得正確的過濾項目。 – mwl

回答

2

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; 
}, []); 
+0

太好了,謝謝!也感謝與'reduce()'的提示 – mwl

+0

不客氣:) –