简体   繁体   English

如何根据来自 api 的数据是否可用有条件地在 React js 中呈现按钮?

[英]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.

相关问题 如何使用React JS中的循环根据条件呈现或不呈现表数据? - How do you render or not render table data based on conditions, using a loop in React JS? 在 React 中,如果 state 是一个空数组,那么如何有条件地呈现文本? - In React, if a state is an empty array then how do you render a text conditionally? 如何有条件地渲染从调用 API 路由的 useEffect 返回的数据并将该数据添加到 useState 变量 - How do I conditionally render data returned from a useEffect that calls an API route and adds that data to a useState variable 如何使用 React js 在表中呈现来自 API 响应的数据 - How to render data from a API response in a table using react js 如何在反应js中有条件地呈现错误? - How to conditionally render error in react js? React Native:你能根据字符串的存在有条件地渲染 JSX 吗? - React Native: Can you conditionally render JSX based on the existence of a string? 如何有条件地渲染 react.js 中的组件? - How to conditionally render a component in react.js? 动态渲染数据并有条件地渲染组件:React JS - Dynamically render data and render components conditionally: React JS 有条件地在 API 中呈现数据 - conditionally render data in an API 如何在 React 中显示来自 api 的数据? - How Do you display data from an api in React?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM