Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
227 views
in Technique[技术] by (71.8m points)

javascript - Reactjs: Cannot read URL property of null, fetching from an API

I have products in json format that are fetched and shown in the frontend. In my products.json there is an image url for each products, but only some have image urls in them, others are empty. When I am looping the data in react I always get error in my react app saying Cannot read property of null in the tag, how do I write a logic that only renders the image when there is an image source else just return an empty div?

<ul>
          {this.state.items.map((items, index) => {
            return (
              <li className="ProductList-product" key={items.id}>
                  <h3>{items.title}</h3>
                  <p>{items.description}</p>
                  <div className="price-box">    
                  <p>from: {items.price} $</p>
                  </div>
                  <div>
                  {<img src={items.photo} alt=""/>}
                  {/* {console.log(items.photo.id)} */}
                  </div>
              </li>
                
            );
          })}
        </ul>
question from:https://stackoverflow.com/questions/65641552/reactjs-cannot-read-url-property-of-null-fetching-from-an-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

replace your

{<img src={items.photo} alt=""/>}

with

{items.photo && <img src={items.photo} alt=""/>}

it will only render img element when item.photo is not null.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...