Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在页面底部获取更多数据_Javascript_Reactjs - Fatal编程技术网

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');}”