开发者问题收集

ReactJs:未捕获的类型错误:无法读取未定义的属性(读取‘0’)

2022-07-08
833

我试图访问 JSON 数据中 payload 中的键和值,如果键存在于数组 countTargetOptions 中,我将在组件中显示它。

但是当我尝试显示数据 {payload[0]?.payload?.countTargetOptions[i]> 时,我一直收到 Uncaught TypeError: Cannot read properties of undefined (reading '0') (注意:在阅读 React: Uncaught TypeError: Cannot read properties of undefined (reading '0') 后,我添加了 ? ,但它仍然不起作用)。

在我尝试循环渲染组件之前,没有问题。请参阅下面的代码和有效载荷数据的照片。

const countTargetOptions = [
  "count_targets",
  "count_targets_excluded",
  "count_targets_pending",
  "count_targets_in_progress",
  "count_targets_completed",
  "count_targets_failed",
];

const CustomTooltip = ({ payload}: TooltipProps<ValueType, NameType> | any) => {

    if( payload && payload.length){
      var targetsData = [];
      let payloadData: any = payload[0].payload;
      for(let i = 0; i < countTargetOptions.length; i++){
        if(payloadData.hasOwnProperty(countTargetOptions[i])){
          let targetOption: string  = countTargetOptions[i].replaceAll('_', ' ');         
          targetsData.push(
          <Typography key = {targetOption} sx={{ fontSize: 14 }} color={"black"} >
          {targetOption} : {payload[0]?.payload?.countTargetOptions[i]}
        </Typography> )

        }
      }
      return (
        <>
        <Card>
          <CardContent>
            {targetsData}

            //Example of what wored before loop
            {/* <Typography sx={{ fontSize: 14 }} color={"black"} >
              count targets : {payload[0].payload.count_targets}
            </Typography> */}
          </CardContent>
        </Card>
        </>
      );
    }
    return null;
  }

在此处输入图片描述

1个回答

您可能想要这样做:

{targetOption} : {payload[0].payload[countTargetOptions[i]]

关于 ?.

?. 是一个运算符,如果左侧为 undefined ,则返回 undefined 。您将其添加到了错误的位置。这样做:

{targetOption} : {payload[0].payload.countTargetOptions?.[i]}

会稍微好一点,因为这样您就不会收到错误,尽管值仍然是 undefined

Konrad
2022-07-08