【问题标题】:Render a promised value for each item in a mapped list为映射列表中的每个项目呈现承诺值
【发布时间】:2021-09-07 05:19:53
【问题描述】:

我正在尝试计算每个缓存中的项目数,并将结果呈现在列表中。我可以 console.log() 结果,但不能渲染它。在这个缓存“瓦片”中有 5 个项目。我已经查看了所有相关问题,但它们都显示了如何 console.log() 来自我可以做的承诺的值,但我无法弄清楚如何呈现数组中每个项目的值。

这些是组件:

// Array passed to  Layers.js

const offlineLayers = [
  {
    title: "Demo Activity",
    url: "tiles/{z}/{x}/{y}.png",
    cacheName: "tiles",
    cacheLength: tiles.length // 2141 items
  }
];
// Layers.js - where the details about each object in ```offlineLayers``` are rendered

const getCache = async (cacheName) => {
  const cache = await (await caches.open(cacheName)).keys();
  return await cache;
};

{offlineLayers && (
    <FormControl className={classes.formControl}>
      <FormLabel>Offline Layers</FormLabel>
      <RadioGroup value={baseValue} onChange={handleBaseChange}>
        {offlineLayers.map((layer, i) => {
          let length;
          getCache(layer.cacheName).then((cache) => {
            console.log(cache.length); // 5 which is the correct number
            return (length = cache.length);
          });
          return (
            <Fragment>
              <FormControlLabel
                className={classes.formControlLabel}
                key={i}
                value={layer.title}
                control={<Radio size="small" />}
                label={layer.title}
              />
              <FormHelperText
                className={classes.offlineCount}
              >{`Downloaded: ${length} / ${layer.cacheLength}`}</FormHelperText>
            </Fragment>
          );
        })}
      </RadioGroup>
    </FormControl>
  )}

我需要lengthofflineLayers 中的每个对象呈现缓存中的项目数。它 console.log()s 是正确的数字 (5),但当前呈现 undefined

感谢您对如何实现这一目标提出任何建议。

【问题讨论】:

    标签: javascript caching es6-promise


    【解决方案1】:

    如果有人有类似的问题,我通过在映射之前将下载的切片数量附加到原始数组来解决它,这比我之前的计划更有意义,即在地图本身期间获取每个图层的切片数量。

      const getCacheLength = () => {
        offlineLayers.map(function (obj) {
          caches.open(obj.cacheName).then(function (cache) {
            cache.keys().then(function (keys) {
              return Object.assign(obj, {
                downloadedLength: keys.length
              });
            });
          });
        });
        return offlineLayers;
      };
    
      const offlineLayersWithCache = offlineLayers && getCacheLength();
    
      // then map the new array offlineLayersWithCache as normal
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-10-31
      • 2022-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 2021-11-23
      • 2015-10-09
      相关资源
      最近更新 更多