Javascript 在页面底部获取更多数据
当页面位于最底部时,我在尝试运行函数时遇到问题。当页面位于最底部时,我试图从数据库中获取更多数据 我的代码结构如下所示Javascript 在页面底部获取更多数据,javascript,reactjs,Javascript,Reactjs,当页面位于最底部时,我在尝试运行函数时遇到问题。当页面位于最底部时,我试图从数据库中获取更多数据 我的代码结构如下所示 constructor(){ super(); this.state = { render_count: 1, } this.getFeed.bind(this); } componentDidMount(){ this.getFeed(); win
constructor(){
super();
this.state = {
render_count: 1,
}
this.getFeed.bind(this);
}
componentDidMount(){
this.getFeed();
window.addEventListener('scroll', function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log("you're at the bottom of the page");
this.setState({render_count: this.state.render_count+1});
this.getFeed();
}
});
}
getFeed(){//get node.js data}
似乎是这样的。状态为null或是出于某种原因。我有个错误
“无法读取未定义的属性'render_count'”
它也不读取this.getFeed()
谢谢你的帮助 function(){}
函数不捕获您需要的此
改用箭头函数:()=>{…}
有关更多详细信息,请参阅
请记住在某些时候也要删除该事件侦听器。当您在
窗口中时,您处于一个新的作用域中。addEventListener('scroll',function(){}
。关键字this
不再指有问题的React类,而是指EventListener
这可以通过使用箭头功能进行修复
window.addEventListener('scroll', () => {})
或将此保存为变量或常量
componentDidMount(){
this.getFeed();
const self = this;
window.addEventListener('scroll', function() {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log("you're at the bottom of the page");
self.setState({render_count: self.state.render_count+1});
self.getFeed();
}
});
}
您需要使用箭头函数来代替<代码>函数()/>代码。也可以考虑使用交叉观察者:您为这个类组件定义了一个构造函数吗?窗口。{我能问一下删除eventlistener的最佳方法是什么吗?我应该这样做吗?“componentWillUnmount(){window.removeEventListener('scroll');}”