我在ReactJs中使用帖子进行无限滚动。
我有一个名为AllPosts
和Post
的反应类。 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 :(得分:1)
这是React擅长的那些令人敬畏的事情之一:)
假设您不想使用Flux / Redux实现,我会将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>
);
}
});
对于其他框架,您必须处理滚动位置(如果元素完全重新渲染,元素会暂时消失并且您的滚动位置会重置)。
React的render
函数实际上并不只是将其输出呈现给DOM;它将潜在输出与已存在的输出进行比较,并仅应用差异。这意味着只有新帖子被添加到DOM中,您的滚动位置将不受影响。