[英]How do you conditionally render a button in React js based on if data from api is avaliable or not?
So, I currently have an API that gives out covid testing center data from an api, and this is accessed through the center prop that is passed to this component.所以,我目前有一个 API,它提供来自 api 的 covid 测试中心数据,这是通过传递给该组件的 center 属性访问的。 I was wondering how to conditionally render the button below based on if there is a phone number field available in the API.我想知道如何根据 API 中是否有可用的电话号码字段来有条件地呈现下面的按钮。 If not, then just not render it.如果没有,那么就不要渲染它。
const TestingCenter = ({ center }) => {
return (
<div className="testing-card">
<h1>{center.title.slice(22)}</h1>
<div>
<h4>{(center.distance / 5280).toFixed(2)} miles away</h4>
<h3>
{center.address.houseNumber} {center.address.street},{" "}
{center.address.city}, {center.address.stateCode}{" "}
{center.address.postalCode}
</h3>
<button>Get Directions</button>
{center.contacts[0].phone[0].value && (
<button
onClick={() => console.log(center.contacts[0].phone[0].value)}
>
Call Site
</button>
)}
</div>
</div>
);
};
export default TestingCenter;
This component TestingCenter is being mapped and displayed once for each testing center available from API.对于 API 提供的每个测试中心,此组件测试中心将被映射和显示一次。 When I try this above I get "TypeError: Cannot read property '0' of undefined."当我在上面尝试这个时,我得到“TypeError:无法读取未定义的属性'0'。”
This may work这可能有效
{center.contacts && center.contacts[0].phone[0].value(
<button
onClick={() => console.log(center.contacts[0].phone[0].value)}
>
Call Site
</button>
)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.