[英]ReactJs: Uncaught TypeError: Cannot read properties of undefined (reading '0')
I am trying to access the key and values in payload
in my JSON data, and if the key is present in array, countTargetOptions
, I will display it in a component.我正在尝试访问 JSON 数据中payload
中的键和值,如果键存在于数组countTargetOptions
中,我将在组件中显示它。
But I keep getting a Uncaught TypeError: Cannot read properties of undefined (reading '0')
when I try to display the data {payload[0]?.payload?.countTargetOptions[i]}
(note: I added the ?
after reading React: Uncaught TypeError: Cannot read properties of undefined (reading '0') but it is still not working).但是当我尝试显示数据{payload[0]?.payload?.countTargetOptions[i]}
时,我不断收到Uncaught TypeError: Cannot read properties of undefined (reading '0')
(注意:我在阅读后添加了?
React: Uncaught TypeError: Cannot read properties of undefined (reading '0') but it still not working)。
Before I tried to render the components in a loop, there was no issues.在我尝试循环渲染组件之前,没有任何问题。 See below my code and a photo of the payload data.请参阅下面的代码和有效负载数据的照片。
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;
}
You probably wanted to do this:你可能想这样做:
{targetOption} : {payload[0].payload[countTargetOptions[i]]
About ?.
关于?.
?.
is an operator that returns undefined
if the left-hand side is undefined
.是一个运算符,如果左侧是undefined
undefined
You added it in the wrong places.你在错误的地方添加了它。 Doing this:这样做:
{targetOption} : {payload[0].payload.countTargetOptions?.[i]}
would be a little bit better, because you wouldn't get the error then, although the value would still be undefined
.会好一点,因为那时你不会得到错误,尽管值仍然是undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.