简体   繁体   English

如何防范 JSX 中未定义的 API 调用值?

[英]How to guard against an undefined API call value in JSX?

I have a component that makes an API call and returns some financial data set as state like so:我有一个组件可以进行 API 调用并返回一些财务数据集为 state,如下所示:

      const [statisticsData, setStatisticsData] = useState({});

which works perfectly, however, the API does not always have all of the data I need to display.效果很好,但是,API 并不总是拥有我需要显示的所有数据。 A basic example of the JSX attempting to be rendered:尝试渲染 JSX 的基本示例:

    <StatBox
        statType="PE Ratio"
        statValue={statisticsData.summaryDetail.PERatio.fmt}
      />

The component renders perfectly when the PE Ratio is defined by the API call, however the API does not always produce a PE ratio.当 PE 比率由 API 调用定义时,组件呈现完美,但是 API 并不总是产生 PE 比率。 I have tried using a ternary operator to check if statisticsData.summaryDetail.PERatio.fmt is defined, which did not work.我尝试使用三元运算符来检查是否定义了statisticsData.summaryDetail.PERatio.fmt ,但这不起作用。 I'm also not even able to get the typeof statisticsData.summaryDetail.PERatio.fmt as it throws a runtime error saying我什至无法获得 typeof statisticsData.summaryDetail.PERatio.fmt因为它会引发运行时错误说

'TypeError: Cannot read property 'fmt' of undefined'. 'TypeError:无法读取未定义的属性'fmt'。

How can I guard against undefined values if the undefined value throws a runtime error before I can even check if it's undefined?如果未定义的值在我检查它是否未定义之前引发运行时错误,我该如何防范未定义的值?

In this case refactor the component like bellow在这种情况下,像下面这样重构组件

<StatBox
    statType="PE Ratio"
    statValue={statisticsData?.summaryDetail?.PERatio?.fmt ?? null}
/>

?? ?? is an operator that identify if the left hand side is undefined and then returns the right hand side.是一个运算符,它标识左侧是否未定义,然后返回右侧。 So the the fmt or PERatio is not defined it will pass null .因此未定义fmtPERatio它将通过null Now handle the null value inside the component accordingly or pass any default value if you want.现在相应地处理组件内的 null 值,或者根据需要传递任何默认值。

<StatBox
    statType="PE Ratio"
    statValue={statisticsData?.summaryDetail?.PERatio?.fmt}
/>

? ? operator checks if the value exists then it goes inside the object otherwise return undefined there is no need for??操作员检查该值是否存在然后它进入 object 否则返回 undefined不需要? null null

in your example statisticsData?.summaryDetail if 'statisticsData' is null then it wont go to 'summaryDetail' if it exists then it will go 'PERatio' and so on.在您的示例中 statisticsData?.summaryDetail 如果 'statisticsData' 是 null 那么它不会 go 到 'summaryDetail' 如果它存在,那么它将是 Z34D1F91FB2E514B8576FABPERA75A 等等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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