【问题标题】:'if' statement in promise `then` sectionPromise `then` 部分中的 'if' 语句
【发布时间】:2018-06-08 16:51:04
【问题描述】:

好的,所以我坚持我认为会更简单的方法,也许我只是看终端太久了!

我已经为我正在做的 React 课程提交了一个项目,并且在代码审查中,审查者建议进行改进,将if 语句检查添加到承诺的then 部分。

审稿人是这么说的:

在 promise 的 'then' 部分检查 if(query === this.state.query) 以确保您不会将内容替换为旧的 回应。

bookSearch(query) {
      if (query.length > 0)
        BooksAPI.search(query)
        .then(searchResults => this.setState(currentState => ({ 
          results: this.updateExistingShelves(searchResults)
        })));
     }

我尝试在其中添加if,但我不断收到语法错误。这样做的正确方法是什么?

我无法在此方法中将其添加到初始的 if,因为它会弄乱第一个查询,并且不会进入 BooksAPI 调用

【问题讨论】:

  • 大概意思是.then(searchResults => { if(query === this.state.query) ...
  • @CertainPerformance,当场。队友的欢呼声。如果您想发布答案,我会检查它

标签: javascript reactjs


【解决方案1】:

我想这就是他的意思:

bookSearch(query) {
      if (query.length > 0)
        BooksAPI.search(query)
        .then(searchResults => {
          if (query === this.state.query) {
            this.setState({ results: this.updateExistingShelves(searchResults) });
          } 

        });
     }

【讨论】:

    【解决方案2】:

    你可以在里面添加一个 if ,然后喜欢,

    bookSearch(query) {
          if (query.length > 0)
            BooksAPI.search(query)
            .then(searchResults => {
                if(query === this.state.query){
                  this.setState(currentState => (
                  { 
                     results: this.updateExistingShelves(searchResults)
                  }))
                }
            );
         }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-20
      • 2017-07-07
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多