npm debounce 在 ReactJS 中失败

npm debounce failing in ReactJS

使用 npm debounce 我在 ReactJS 中收到以下代码的错误。错误

Javascript - Uncaught TypeError: Object(...) is not a function

函数传入 debounce() 时发生

import React, { Component } from 'react';
import { debounce } from 'debounce';

class test extends Component {
     constructor(props) {
         super(props);
         this.state = {
             yolo: {}
         };
     }

     foobar(param) {
         debounce(() => {
             this.setState({yolo: param});
         }, 99);
     }

     render () {
         return (
             ...
             <SomeComponent action={this.foobar.bind(this)} />
             ...
         );
     }
}

我已经尝试了Perform debounce in React.js中提到的一些解决方案 但 none 似乎有效。

import React, { Component } from 'react';
import debounce from 'debounce';

class test extends Component {
     constructor(props) {
         super(props);
         this.state = {
             yolo: {}
         };
         this.foobar.bind(this);
     }

     foobar(param) {
         debounce(() => {
             this.setState({yolo: param});
         }, 99);
     }

     render () {
         return (
             ...
             <SomeComponent action={this.foobar.bind(this)} />
             ...
         );
     }
}

最上面的一组代码应该可以工作。好的,所以你之前对 foobar 的调用不起作用的原因是你错过了这一行:this.foobar.bind(this);。您以前的语法工作得很好,实际上比 this.foobar = 更可取。原因是因为一个是 ES6 语法,另一个是 ES5。当您调用绑定函数时,绑定函数的作用是在调用该函数时附加一个特定的 this 上下文。这是对解释该内容的文章的引用:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

现在第二部分是导入。当您使用对象括号语法时,这实际上称为对象解构。因此,无论该对象导出什么,它都会尝试访问去抖动 属性 并使其在当前文件中可访问。问题是我怀疑那个 npm 包已经导出一个函数作为它的默认值,所以你不需要访问它上面的东西。说得通?

希望这对您有所帮助!祝你好运(点赞)