【问题标题】:Issues with setting a const using lodash _.map使用 lodash _.map 设置 const 的问题
【发布时间】:2021-10-06 08:01:38
【问题描述】:

我在从 Algolia multipleQueries 搜索选项获取结果后尝试设置一个变量。

结果是一个对象,我解构它得到 2 个数组。

我通过它进行映射并将返回设置为具有“nbHits”的数组

  const results = await algolia
        .multipleQueries(searchOptions, {
          strategy: "stopIfEnoughMatches",
        })
        .then(({ results }) => {
          console.log("Step 1", results);
          _.map(results, result => {
            console.log(" Step 2", _.get(result, "nbHits"));
            if (_.get(result, "nbHits") != 0) {
              console.log(" Step 3", _.get(result, "hits"));
              return _.get(result, "hits");
            }
          });
        });
      console.log("Step 4", results);


Step 1

 [ {
  nbHits: 421,
  hits: 1000,
 }, 
 {
  nbHits: 0,
  hits: 0,
 } ]

Step 2 : 421

Step 3 : "An array with the hits"

Step 2 : 0

Step 4 : Undefined 

我做错了什么导致返回值将 const 结果设置为未定义。

这行得通:

const results = await algolia
        .multipleQueries(searchOptions, {
          strategy: "stopIfEnoughMatches",
        })
      console.log(results);

【问题讨论】:

  • 您从未返回地图的结果。你应该在_.map前面加上return

标签: javascript reactjs async-await lodash algolia


【解决方案1】:

您需要在 .then() 块内返回 _.map 调用。

const results = await algolia
  .multipleQueries(searchOptions, {
    strategy: "stopIfEnoughMatches",
  })
  .then(({ results }) => {
    return _.map(results, (result) => {
      if (_.get(result, "nbHits") != 0) {
        return _.get(result, "hits");
      }
    });
  });

附带说明:在_.map 内部,只有当_.get(result, "nbHits") != 0 为真时才会返回一个值,在其他情况下,您将使用其中的undefined 值填充数组,因此请考虑使用_.filter 将它们取出.

【讨论】:

    【解决方案2】:

    这为我解决了问题,改用 lodash 过滤器

    const results = await algolia
            .multipleQueries(searchOptions, {
              strategy: "stopIfEnoughMatches",
            })
            .then(({ results }) => {
              return _.filter(results, result => result.nbHits != 0);
    

    【讨论】:

      猜你喜欢
      • 2023-02-24
      • 2017-11-05
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 1970-01-01
      • 2019-02-13
      • 2010-12-07
      • 2022-01-10
      相关资源
      最近更新 更多