javascript - Anonymous function error on Google Maps API marker click
问题描述
Using Foursquare Google Maps APIs, my goal is to use the venue photo property provided by Foursquare and, if it's available in a venue's metadata, to render it along with the venue's name within the Google Maps API info window. If only one of the two properties are available, I want to render the available one only. If the venueInfo is undefined or neither property is available, I want to simply display "No info available" in the info window. I tried doing this with a conditional operator with multiple conditions.
For at least one marker, sometimes the info will display, but sometimes I get these errors.
I don't understand what's wrong or how to fix it. If the 'name' property is undefined, shouldn't the conditional just make it fall back to display "No info available"? And if the info for the marker displayed fine previously, how can it stop working when I click the same marker again?
Here's my conditional statement for rendering inside the info window:
<InfoWindow>
{venueInfo.name && venueInfo.bestPhoto ?
<Fragment>
<p>{venueInfo.name}</p>
<img src={`${venueInfo.bestPhoto.prefix}200x200${venueInfo.bestPhoto.suffix}`}
alt={"Venue"}
/>
</Fragment> : venueInfo.name ? <p>{venueInfo.name}</p> : venueInfo && venueInfo.bestPhoto ? <img src={`${venueInfo.bestPhoto.prefix}200x200${venueInfo.bestPhoto.suffix}`}
// Screen readers already announce as image; don't need the word "image", "photo", etc.
alt={"Venue"}
/> : <p>No info available</p>}
</InfoWindow>
For reference here's the full component code on GitHub.
解决方案
The error you get is caused by trying to access a property of a value which is undefined.
What that means in your case is that venueInfo
is actually undefined when trying to access venuInfo.bestPhoto
. Which would cause the crash and not the conditional operator.
推荐阅读
- javascript - 对象被推送到数组后发生变化
- azure - 如何确保文件在发布到 Azure 时得到更新?
- vue.js - 在 Vue 3 的插件中创建全局计算属性
- node.js - 在聚合管道的项目阶段排除嵌套对象属性时遇到问题
- ethereum - Rinkeby Authenticated Faucet 不能与 Metamask 一起使用?
- excel - 从日期范围内的某月某日的相邻单元格获取美元值
- javascript - 如何从 JavaScript 对象内部访问属于同一对象的属性?
- react-native - 有没有办法在 expo react native 中使用线性加速?
- jupyter-notebook - 我下载了pycharm专业版,但是还是不能使用jupyter notebook。页面看起来还是社区版
- python - ntplib PermissionError: [Errno 1] 不允许操作