【问题标题】:Normalizr : Only add item to items array if the id is presentNormalizr :如果 id 存在,则仅将项目添加到项目数组
【发布时间】:2019-11-23 21:15:39
【问题描述】:

如何防止向实体添加值或将其推送到items 数组?

我尝试从idAttribute 返回undefined,但它仍然将undefined 推送到items 数组中,并且还在实体中添加了一个名为undefined 的键。

const getGuid = (entity: any) => {
  if (entity.enclosure) {
    if (entity.guid) {
      return entity.guid
    } else if (entity.enclosure.url) {
      return entity.enclosure.url
    }
  }
}

const fetchPodcastRssEpisodeSchema = new schema.Entity(
  'episodes',
  {},
  {
    idAttribute: getGuid,
    processStrategy: (entity, parent, _key) => {
      const itunes = entity.itunes || {}
      const enclosure = entity.enclosure || {}

      const image =
        itunes.image ||
        (parent.image && parent.image.url) ||
        (parent.itunes && parent.itunes.image)

      return {
        artist: parent.title,
        content: entity.content,
        durationSeconds: utils.transformDurationToSecs(itunes.duration),
        guid: getGuid(entity),
        image,
        pubDate: entity.isoDate,
        title: entity.title,
        url: enclosure.url,
      }
    },
  }
)

只有在从idAttribute 返回有效值时才应添加该项目。有什么办法可以实现吗?

谢谢

【问题讨论】:

  • 你能展示一下代码吗?

标签: reactjs redux react-redux normalizr


【解决方案1】:

更新

const getGuid = (entity: any) => {
   if (entity && entity.enclosure) {
     if (entity && entity.guid) {
       return entity.guid
     } else if (entity && entity.enclosure && entity.enclosure.url) {
       return entity.enclosure.url
      }
    }
 }

【讨论】:

  • 这可能是一个更好的写法,但它仍然不能解决问题,即 undefined 将被添加到 items 数组中
  • 我觉得解释不清楚。让我再解释一下。我不想要一个值为undefined 的项目。在这里,如果 entity && entity.enclosure 为 false,则将返回 undefined,并将其推送到我不想要的 items 数组中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 1970-01-01
  • 1970-01-01
  • 2012-03-25
  • 2020-10-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多