Lodash反跳异步/等待

时间:2019-09-23 02:52:02

标签: javascript reactjs lodash debounce

在尝试进行api调用之前,我试图将反跳功能添加到我的应用程序中。但是,当我引入debouce时,似乎我的等待被忽略了,并且由于缺少值而调用了函数

export default class App extends Component {
  state = {
    search: "Cats",
    results: []
  };

  async search(text) {
    const giphy = {
      baseURL: "https://api.giphy.com/v1/gifs/search",
      apiKey: "0UTRbFtkMxAplrohufYco5IY74U8hOes",
      tag: text
    };

    let giphyURL = encodeURI(
      giphy.baseURL + "?api_key=" + giphy.apiKey + "&q=" + giphy.tag
    );

    let data = await fetch(giphyURL);
    return data.json();
  }

  async componentDidMount() {
    // get default search
    this.onSearch(this.state.text);
  }

  setSearch = e => {
    this.setState({ search: e.target.value });

    debounce(() => this.onSearch(this.state.search), 100);
  };

  async onSearch(text) {
    console.log("text:", text);
    try {
      let response = await this.search(this.state.search);
      console.log("data:", response.data);
      // console.log(data.results);

      let data = response.data.reduce((t, { title, id, images }) => {
        t.push({ title, id, url: images.downsized_medium.url });
        return t;
      }, []);
      this.setState({ results: data });
    } catch (e) {
      console.error("Failed Fetch", e.toString());
    }
  }

  render() {
    return (
      <main className="app">
        <Header>This is my Gif Search App</Header>
        <nav className="navbar">
          <SearchBox onSearch={this.setSearch} value={this.state.search} />
        </nav>
        <aside className="sidebar">Sidebar Bar</aside>
        <section className="results">
          <Results results={this.state.results} />
        </section>
        <footer className="footer">
          <p className="footer-text">Copyright @funssies 2019</p>
        </footer>
      </main>
    );
  }
}

错误:在setSearch方法中,我包装了调用以防抖动来获取数据,但没有任何反应。

2 个答案:

答案 0 :(得分:1)

我想我明白了。 Deboune返回一个函数。然后我必须调用该功能

例如:

let myFunc = debounce(this.someFunction,100)

// call debounced function 
myFunc()

我将功能更改为此:

  delayedSearch = debounce(this.onSearch, 1500);

  setSearch = e => {
    this.setState({ search: e.target.value });

    this.delayedSearch(this.state.search);
  };

在此处找到帮助:lodash debounce not working in anonymous function

答案 1 :(得分:0)

onSearch是一个异步功能。去抖的参数函数也必须是异步的。是的,就像蝙蝠侠指出的那样。

const debouncedOnSearch = debounce(async () => {
         this.onSearch(this.state.search)
    }, 100);
setSearch = e => {
    this.setState({ search: e.target.value });
    debouncedOnSearch();

  };

这应该有效。另一个类似的问题我found

希望这会有所帮助。