【问题标题】:npm debounce failing in ReactJSReactJS 中的 npm debounce 失败
【发布时间】:2019-03-15 20:48:25
【问题描述】:

使用 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中提到的一些解决方案 但似乎没有一个工作。

【问题讨论】:

  • 你能展示你的进口吗?
  • 现在应该是 fobar = debounce((param) =&gt; ...);,你传递给 debounce 的函数永远不会被调用
  • @AndreKnob 完成
  • 介意试试这个import debounce from 'debounce';?我知道 github repo 说要使用其他语法,但请尝试一下。
  • @m.a.solano93 确实有效,还有 foobar = debounce(param => {}, 99);您介意创建答案来解释原因吗?我必须承认我不完全确定进口方式的不同。

标签: javascript reactjs npm debounce


【解决方案1】:
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 包已经将一个函数导出为它的默认值,所以你不需要访问它上面的东西。有道理?

希望这对您有所帮助!祝你好运(竖起大拇指)

【讨论】:

    猜你喜欢
    • 2018-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-01-22
    • 2021-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    相关资源
    最近更新 更多