简体   繁体   中英

How to check data exist to in order to render a result?

This is my code here : XXXXX sorry code no longer available will include soon.

What I would like to happen is when I click a button the 'index' of each object is passed like this:

const priceShown = product[evenIndex].price;

But when the pages loads I get an error saying price is undefined :(

I know its something to do with the data not existing yet (I have little knowledge as to why this is a thing so if you could also explain this would be a great bonus too!) .

To check if the data is there before priceShown I wrote this:

if (evenIndex !== null) {
  return evenIndex;
} else {
   console.log('no data');
}; 

This returns the no data part of the statement always as you can't pass an index ( evenIndex ) unless you click on a button, so price will always be undefined? Unless its undefined for another reason of which I do not know.

Any Help?

You can check if product[evenIndex] is set first, and then take out the price if it is. This way no price will be rendered until an index has been selected.

const priceShown = product[evenIndex] && product[evenIndex].price;

You need to verify whether evenIndex even exists before trying to access the product array. You can even get rid of evenIndex as it serves no use in your example.

const priceShown =
  this.state.evenSelected == null
    ? "No data"
    : product[this.state.evenSelected].price;

Here's an updated version of the code you linked: https://codesandbox.io/s/kmw7npp7z5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM