2016-03-05 54 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 –