2016-03-05 87 views
2

無限滾動我在帖子ReactJs作出無限滾動。追加到reactJs

我有一個名爲AllPostsPost一個反應類。 AllPosts呈現多個Post s。

我有這樣的代碼:

ReactDOM.render(
    <AllPosts data={posts} />, 
    document.querySelector(render_to) 
); 

並在下面的方法

// Render all posts 
var AllPosts = React.createClass({ 

    render: function() { 
     return (
      <div> 
       {this.props.data.map(function(element, i) { 
        return <Post data={element} /> 
       })} 
      </div> 
     ); ..... 

但是,我有滾動的事件,我想追加相互反應後。我怎樣才能做到這一點?

回答

0

這是那些真棒事情之一陣營在:)

在您不想使用助焊劑/終極版實現的假設是偉大的,我將設置posts數據作爲你的根狀態零件。這樣,當posts變化,該組件將重新渲染:

var AllPosts = React.createClass({ 
    getInitialState() { 
    // Start with an empty array of posts. 
    // Ideally, you want this component to do the data fetching. 
    // If the data comes from a non-react source, as in your example, 
    // you can do `posts: this.props.posts`, but this is an anti-pattern. 
    return { posts: [] } 
    }, 

    componentWillMount() { 
    // Fetch the initial list of posts 
    // I'm assuming here that you have some external method that fetches 
    // the posts, and returns them in a callback. 
    // (Sorry for the arrow functions, it's just so much neater with them!) 
    ajaxMethodToFetchPosts(posts => { 
     this.setState({ posts: posts }); 
    }) 
    }, 

    componentDidMount() { 
    // Attach your scroll handler here, to fetch new posts 
    // In a real example you'll want to throttle this to avoid too many requests 
    window.addEventListener('scroll',() => { 
     ajaxMethodToFetchPosts(posts => { 
     this.setState({ 
      posts: this.state.posts.slice().concat(posts) 
     }); 
     }); 
    }); 
    }, 

    render() { 
    // Render method unchanged :) 
    return (
     <div> 
     {this.props.data.map(function(element, i) { 
      return <Post data={element} /> 
     })} 
     </div>   
    ); 
    } 
}); 

與其他框架,你必須處理滾動位置(如果該元素被完全重新繪製,元素瞬間消失,你的滾動位置被重置)。

陣營的render功能實際上並不只是呈現其輸出到DOM;它將潛在產出與已有產出進行比較,並僅應用差異。這意味着,只有新的職位將被添加到DOM,你的滾動位置將不受影響。

+0

感謝的人!適用於我= D –