2016-09-04 51 views
1

我有导入debounce库合适到react + typescript项目的问题。reactJs + typescript + debounce - 无法正常导入debounce

我做:

  1. npm install debounce --save
  2. typings install dt~debounce --save --global
  3. 在我的文件,导入防抖动为:import debounce from 'debounce';
  4. 使用反跳这样的:debounce(function(){ console.log('testtt'); })();

有了这些代码我的代码compllation传递,但当我试图运行我们bside我得到错误:

Uncaught TypeError: debounce_1.default is not a function

我到底做错了什么?

感谢

回答

1

我想通了,lodash库具有debounce功能和打字稿一分型。

它的工作原理是这样的:

import _ = require('lodash'); 

... 

class SearchControl extends React.Component<ISearchControlProps, ISearchControlState> { 
    private debouncedLoadSuggestions; 
    constructor(props: any) { 
     ... 
     this.debouncedLoadSuggestions = _.debounce(this.fetchSuggestions, 500); 
    } 

    fetchSuggestions = (value: string) => { 
     ... 
    }; 

    onSuggestionsFetchRequested = ({value}) => { 
     this.debouncedLoadSuggestions(value); 
    }; 
} 
0

我只是碰到了这个问题为好。看起来debounce的类型只是错误的,也许是对于过时的非模块版本的库。我并不倾向于在所有的lodash带来只是这个功能,所以在未来的人,这些分型为我工作:

declare module "debounce" { 
    function debounce<F extends Function>(func: F, wait?: number, immediate?: boolean): F; 
    namespace debounce {} 
    export = debounce; 
} 

例子:

import * as debounce from "debounce"; 

document.body.addEventListener("mousemove", debounce((e: MouseEvent) => console.log("moved"), 500));