使用JavaScript的可选链接来有条件地从API渲染图像。

huangapple go评论65阅读模式
英文:

Using JavaScript's optional chaining to conditionally render an image from an API

问题

I'm working on building a very basic news app using the New York Times' 'top stories' API. The API is well documented and there are plenty of examples of how to get stared online. But I'm stuck with conditionally rendering an image. Some of the objects in the API do not contain image files. In those cases, I need to render a generic "no image available" .png file. I'm really new to React and APIs so still learning the basics.

My code is throwing this error: Uncaught TypeError: Cannot read properties of undefined (reading 'media-metadata').

I'm trying to conditionally render an image using JS Optional Chaining. This is what I have so far.

   <div className="card">
                
                  
                    {title}
                    <ImageFormat className={media} component="img" src={media[0]['media-metadata'][2]?.url ?
                    `${media[0]['media-metadata'][2].url}` : 'https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png'
                    }/>
                    {/* <img src={media[0]['media-metadata'][2].url} />  */}
                    <div className="facet">
                    {des_facet}
                    </div>
            </div>   

My logic is this: if the object contains the img file then it will render, if not, then render the png file.

As stated above, I've tried using JS optional chaining (which is a very new concept for me). The error is Uncaught Type Error: Cannot read properties of undefined (reading 'reading 'media-metadata')

英文:

I'm working on building a very basic news app using the New York Times' 'top stories' API. The API is well documented and there are plenty of examples of how to get stared online. But I'm stuck with conditionally rendering an image. Some of the objects in the API do not contain image files. In those cases, I need to render a generic "no image available" .png file. I'm really new to React and APIs so still learning the basics.

My code is throwing this error: Uncaught TypeError: Cannot read properties of undefined (reading 'media-metadata').

I'm trying to conditionally render an image using JS Optional Chaining. This is what I have so far.

   <div className="card">
                
                  
                    {title}
                    <ImageFormat className={media} component="img" src={media[0]['media-metadata'][2]?.url ?
                    `${media[0]['media-metadata'][2].url}` : 'https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png'
                    }/>
                    {/* <img src={media[0]['media-metadata'][2].url} />  */}
                    <div className="facet">
                    {des_facet}
                    </div>
            </div>   

My logic is this: if the object contains the img file then it will render, if not, then render the png file.

As stated above, I've tried using JS optional chaining (which is a very new concept for me). The error is Uncaught Type Error: Cannot read properties of undefined (reading 'reading 'media-metadata')

答案1

得分: 0

以下是您要翻译的代码部分:

while using the `&&` operator to check if each property is defined before accessing it. This way, if any of the properties are undefined, the code won't throw an error and will instead skip over the image rendering.

<div className="card">
  {title}
  {media && media[0] && media[0]['media-metadata'] && (
    <ImageFormat
      className={media}
      component="img"
      src={
        media[0]['media-metadata'][2]?.url
          ? `${media[0]['media-metadata'][2].url}`
          : 'https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png'
      }
    />
  )}
  <div className="facet">{des_facet}</div>
</div>
英文:

while using the &amp;&amp; operator to check if each property is defined before accessing it. This way, if any of the properties are undefined, the code won't throw an error and will instead skip over the image rendering.

&lt;div className=&quot;card&quot;&gt;
  {title}
  {media &amp;&amp; media[0] &amp;&amp; media[0][&#39;media-metadata&#39;] &amp;&amp; (
    &lt;ImageFormat
      className={media}
      component=&quot;img&quot;
      src={
        media[0][&#39;media-metadata&#39;][2]?.url
          ? `${media[0][&#39;media-metadata&#39;][2].url}`
          : &#39;https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png&#39;
      }
    /&gt;
  )}
  &lt;div className=&quot;facet&quot;&gt;{des_facet}&lt;/div&gt;
&lt;/div&gt;

答案2

得分: 0

看起来 media[0]undefined,你需要使用 ?. 进行可选链操作。

   &lt;div className=&quot;card&quot;&gt;
      {title}
      &lt;ImageFormat className={media} component=&quot;img&quot; src={media?.[0]?.['media-metadata']?.[2]?.url ? `${media[0]['media-metadata'][2].url}` : 'https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png'}/&gt;
      &lt;div className=&quot;facet&quot;&gt;
        {des_facet}
      &lt;/div&gt;
   &lt;/div&gt; 
英文:

It looks like media[0] is undefined you need to optionally chain it with ?..

   &lt;div className=&quot;card&quot;&gt;
      {title}
      &lt;ImageFormat className={media} component=&quot;img&quot; src={media?.[0]?.[&#39;media-metadata&#39;]?.[2]?.url ? `${media[0][&#39;media-metadata&#39;][2].url}` : &#39;https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png&#39;}/&gt;
      &lt;div className=&quot;facet&quot;&gt;
        {des_facet}
      &lt;/div&gt;
   &lt;/div&gt; 

答案3

得分: 0

如果media被初始化为一个数组,可以使用以下方式。不要使用三元运算符,因为它会导致我们重复相同的条件语句两次,而是使用**||**(或)运算符。如果之前的值为假(即未定义、null、0或""),它将继续并选择下一个。

src={media[0]?.['media-metadata']?.[2]?.url || "https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png"}

如果media可以是未定义或null,那么可以使用以下方式。

src={media?.[0]?.['media-metadata']?.[2]?.url || "https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png"}
英文:

If media is initialized as an Array.
Use this. Instead of using ternary here as it makes us to repeat same conditional statement twice,use || (OR) operator. If previous value is falsy (i.e undefined, null, 0, "") it will move forward and pick next.

src={media[0]?.[&#39;media-metadata&#39;]?.[2]?.url || &quot;https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png&quot;}

If media can be undefined or null then use this.

src={media?.[0]?.[&#39;media-metadata&#39;]?.[2]?.url || &quot;https://upload.wikimedia.org/wikipedia/commons/e/e0/Red_Exclamation_Dot.png&quot;}

huangapple
  • 本文由 发表于 2023年2月18日 01:30:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75487482.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定