[英]How to stop page from scrolling when loading new data
I have a class component in react that maps Post components.我有一个 class 组件用于映射 Post 组件。 At the bottom, I have a button that loads more data from the database.在底部,我有一个从数据库加载更多数据的按钮。 The problem I am having is that when the new data is loaded the page is scrolled to the bottom.我遇到的问题是,当加载新数据时,页面滚动到底部。 I want to have it stick to the post where the user was previously我想让它坚持用户以前的帖子
My component:我的组件:
import React,{Component} from 'react';
import Ride from '../Components/Ride';
import firebase from 'firebase'
class RideList extends Component{
state={
rides: [{
user:{
photo: '',
name: '',
uid: ''
},
likes: 0,
likers: [],
time: '',
line: [{lng:22.01,lat:41.01}],
when: 0
}],
lastDoc: {}
}
componentDidMount(){
const db = firebase.firestore();
db.collection('posts').orderBy('when','desc').limit(5).get().then(res=>{
const data = []
res.docs.map(doc=>{
data.push({...doc.data(),id: doc.id})
})
this.setState({rides: data, lastDoc: res.docs[res.docs.length-1]})
}).catch(er=>{
console.log(er)
})
}
loadMore = ()=>{
const rides = [...this.state.rides];
const db = firebase.firestore();
db.collection('posts').orderBy('when','desc').startAfter(this.state.lastDoc).limit(5).get().then(res=>{
res.docs.map(doc=>{
rides.push({...doc.data(),id: doc.id})
})
this.setState({rides: rides, lastDoc: res.docs[res.docs.length-1]})
})
}
render(){
return(
<div style={{textAlign:'start'}}>
{this.state.rides.map((el,index)=>{
return(
<div>
<Ride key={el.when} {...el} user={this.props.user}/>
</div>
)
})}
{this.props.uid ? '':<button onClick={()=>this.loadMore()}>Load more</button>}
</div>
)
}
}
export default RideList;
You should check to "React LifeCycle" documentation.您应该查看“React LifeCycle”文档。 And I think this article helps you.我认为这篇文章对你有帮助。
https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate https://reactjs.org/docs/react-component.html#getsnapshotbeforeupdate
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.