最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ReactJS if prop exists - Stack Overflow

programmeradmin3浏览0评论

at the moment I am getting an error with React because I am mapping an array of objects from a REST end point and some of the objects in the array don't have certain props.

An example is that some of my objects have another object within them called imagesand some don't. When my React ponent tries to render the objects without the images I am left with an error undefined prop.

Here is my ponent that renders my prop:

const VehicleDetail = (props) => {
  return (
    <div className={"col-flex-md-3 col-flex-sm-4 col-flex-xs-6 col-flex-media-query vehicle-item " + props.vehicle.brand.name} data-value={props.vehicle.brand.name}>
      <div className="vehicle-container">
        <img src={"/" + props.vehicle.offers[0].image.name} />
        <h4 className="vehicle-title">
          {props.vehicle.model.name}
        </h4>
        <div className="row-flex">
          <div className="col-flex-xs-12 btn-container">
            <a href={"http://beaver" + props.vehicle.brand.name + ".co.uk/new/cars/" + props.vehicle.slug} target="_blank" className="learn-more-btn">Learn More</a>
          </div>
        </div>
      </div>
    </div>
  );
};

So as you can see I have an img element with a prop of props.vehicle.offers[0].image.name however this fails as some of my objects don't have this object available.

So far I have tried adding an inline conditional just to see if the object existed first however this failed with an error:

<img src={"/" + {if (typeof props.vehicle.offers[0].image.name == "object") { props.vehicle.offers[0].image.name }}} />

Here is my ponent that iterates over each object and renders them to my VehicleDetail ponent:

// Vehicle List Component
import VehicleDetail from './vehicle-detail.js';

// Create our ponent
const VehicleList = (props) => {
  // Just add props.vehicle to access API data instead of static
  const RenderedVehicles = props.vehicles.map(vehicle =>
    <VehicleDetail key={vehicle.slug} vehicle={vehicle} />
  );

  return (
    <div className="row-flex center-xs">
      {RenderedVehicles}
      {console.log(props.brandSelect)}
    </div>
  );
};

Any idea what the best practice in React JS is to do this? Thanks

at the moment I am getting an error with React because I am mapping an array of objects from a REST end point and some of the objects in the array don't have certain props.

An example is that some of my objects have another object within them called imagesand some don't. When my React ponent tries to render the objects without the images I am left with an error undefined prop.

Here is my ponent that renders my prop:

const VehicleDetail = (props) => {
  return (
    <div className={"col-flex-md-3 col-flex-sm-4 col-flex-xs-6 col-flex-media-query vehicle-item " + props.vehicle.brand.name} data-value={props.vehicle.brand.name}>
      <div className="vehicle-container">
        <img src={"https://s3-eu-west-1.amazonaws./pulman-vw-images/uploads/images/thumbnails/" + props.vehicle.offers[0].image.name} />
        <h4 className="vehicle-title">
          {props.vehicle.model.name}
        </h4>
        <div className="row-flex">
          <div className="col-flex-xs-12 btn-container">
            <a href={"http://beaver" + props.vehicle.brand.name + ".co.uk/new/cars/" + props.vehicle.slug} target="_blank" className="learn-more-btn">Learn More</a>
          </div>
        </div>
      </div>
    </div>
  );
};

So as you can see I have an img element with a prop of props.vehicle.offers[0].image.name however this fails as some of my objects don't have this object available.

So far I have tried adding an inline conditional just to see if the object existed first however this failed with an error:

<img src={"https://s3-eu-west-1.amazonaws./pulman-vw-images/uploads/images/thumbnails/" + {if (typeof props.vehicle.offers[0].image.name == "object") { props.vehicle.offers[0].image.name }}} />

Here is my ponent that iterates over each object and renders them to my VehicleDetail ponent:

// Vehicle List Component
import VehicleDetail from './vehicle-detail.js';

// Create our ponent
const VehicleList = (props) => {
  // Just add props.vehicle to access API data instead of static
  const RenderedVehicles = props.vehicles.map(vehicle =>
    <VehicleDetail key={vehicle.slug} vehicle={vehicle} />
  );

  return (
    <div className="row-flex center-xs">
      {RenderedVehicles}
      {console.log(props.brandSelect)}
    </div>
  );
};

Any idea what the best practice in React JS is to do this? Thanks

Share Improve this question asked Jul 27, 2016 at 8:24 Nick MaddrenNick Maddren 5832 gold badges7 silver badges20 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

Check the length of offers before rendering.

{props.vehicle.offers.length > 0 ? (
  <img src={url + props.vehicle.offers[0].image.name} />
) : null}

I'd do it like this. In your vehicle ponent declare a variable that would hold the thumbnail url.

const VehicleDetail = (props) => {
  let vehicleThumbnail = '';

  if (props.vehicle.offers[0].image && props.vehicle.offers[0].image.name) {
     vehicleThumbnail = props.vehicle.offers[0].image.name;
  }


  return (
    <div className={"col-flex-md-3 col-flex-sm-4 col-flex-xs-6 col-flex-media-query vehicle-item " + props.vehicle.brand.name} data-value={props.vehicle.brand.name}>
      <div className="vehicle-container">
        <img src={vehicleThumbnail} />
        <h4 className="vehicle-title">
          {props.vehicle.model.name}
        </h4>
        <div className="row-flex">
          <div className="col-flex-xs-12 btn-container">
            <a href={"http://beaver" + props.vehicle.brand.name + ".co.uk/new/cars/" + props.vehicle.slug} target="_blank" className="learn-more-btn">Learn More</a>
          </div>
        </div>
      </div>
    </div>
  );
};

I'd also do the same for the other props.

The normal case of props.vehicle.offers[0] may looks like this:

{
  image: {
    name: 'hello'
  }
}

So, you can use props.vehicle.offers[0].image.name without any error.

But some cases are:

{
  anotherProperty: {

  }
}

props.vehicle.offers[0].image is null, so props.vehicle.offers[0].image.name equals to null.name, which throw the error.

A simple way to solve the problem is something like this:

{ props.vehicle.offers[0].image && <img src={"https://s3-eu-west-1.amazonaws./pulman-vw-images/uploads/images/thumbnails/" + props.vehicle.offers[0].image.name} /> }

If props.vehicle.offers[0].image is null, the statement after && will not be execute, and return nothing to render.

So, it render img element when props.vehicle.offers[0].image is not null, preventing the error.

发布评论

评论列表(0)

  1. 暂无评论