簡體   English   中英

React Native 條件渲染

[英]React Native conditional render

我目前有一個 IMAGES 數組,如果索引存在,它應該顯示圖像。 在當前的實現中,如果存在帶有圖像的索引,則顯示圖像,而對於沒有圖像的索引,則會顯示黑屏。

如何更改我的代碼,以便如果圖像不存在,它不會被添加到數組中?

這是我的代碼:

const IMAGES = [
  post.images[1]
    ? {
        url: post.images[1].url,
      }
    : [],
  post.images[2]
    ? {
        url: post.images[2].url,
      }
    : [],
  post.images[3]
    ? {
        url: post.images[3].url,
      }
    : [],
  post.images[4]
    ? {
        url: post.images[4].url,
      }
    : [],
  post.images[5]
    ? {
        url: post.images[5].url,
      }
    : [],
  post.images[6]
    ? {
        url: post.images[6].url,
      }
    : [],
  post.images[7]
    ? {
        url: post.images[7].url,
      }
    : [],
];
let IMAGES = [];
post?.images &&
  post.images.length > 0 &&
  post.images.map((eachImage, index) => {
    if ("url" in eachImage) {
      IMAGES.push(eachImage.url);
    }
  });

這應該做你想要的:

const IMAGES = [];
post.images && post.images.map(image => {
    if(image && image.url) {
        IMAGES.push({url: image.url})
    }
})

您可以使用過濾器

> post={}
 {}

> post.images ? post.images.filter( ele => ele.url) : null
 null

> post={ images:[ {}, {"url":"abc"}, {}, {"url": "cde"} ]}
 {images: Array(4)}

> post.images ? post.images.filter( ele => ele.url) : null
  (2) [{…}, {…}]


解決方案

 const posts = { images: [ { url: "https//1", }, { url: "https//2", }, {}, { url: "https//3", }, null, { url: "https//4", }, ], }; const images = posts.images.map((item) => (item && item.url? {url:item.url}: [])); console.log(images)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM