Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 类型';字符串[]|未定义';不可分配给类型';字符串[]';。即使我';我用的是?。(可选)_Reactjs_Typescript - Fatal编程技术网

Reactjs 类型';字符串[]|未定义';不可分配给类型';字符串[]';。即使我';我用的是?。(可选)

Reactjs 类型';字符串[]|未定义';不可分配给类型';字符串[]';。即使我';我用的是?。(可选),reactjs,typescript,Reactjs,Typescript,我已经为我的React Component道具构建了类型 export type EventObj { id: string observations?: string[] note?: string } 我在我的React组件中使用这些组件,如下所示: <GameCard id={game.id} observations={game.observations} //gets highlighted by TS note={game.note} //gets

我已经为我的React Component道具构建了类型

export type EventObj {
  id: string
  observations?: string[]
  note?: string
}
我在我的React组件中使用这些组件,如下所示:

<GameCard 
  id={game.id}
  observations={game.observations} //gets highlighted by TS
  note={game.note} //gets highlighted by TS
/>

我甚至试过做
observations?:string[]| undefined
,但这并不能解决问题

如果
observations
可能是未定义的,你不能假设它是一个数组,就把它映射到
上。这就是编译器警告您的。相反,您需要在尝试映射
之前防止未定义,或者在呈现整个组件之前防止
未定义(取决于您的用例)

在下面的示例中,我们确保在呈现
游戏卡之前存在
观察值
注释

{game.note && game.observations && <GameCard 
  id={game.id}
  observations={game.observations}
  note={game.note}
/>}
{game.note&&game.observations&&}

什么是
游戏
?如果
观察值
可能是未定义的,你不能假设它是一个数组,就把它映射到
上面。这就是编译器警告您的。相反,您需要在尝试“<代码> map 之前防止未定义,或者在呈现整个组件之前(根据您的用例)防范<代码>未定义< /代码>。您可以在一个打印文本中放置一个工作示例吗?请考虑修改这个问题中的代码,以便构成一个当放入一个独立的IDE(如IDE)中时,可以清楚地显示您所面临的问题。(例如,您的
类型
定义有语法错误;这不是唯一的问题)这将允许希望帮助您的人立即着手解决问题,而无需首先重新创建。它将使您得到的任何答案都可以根据定义良好的用例进行测试。非常有用!在尝试映射之前,如何防止未定义?可以执行
observations?.map(item=>{item})
observations&&observations.map(item=>{item})
Type 'string[] | undefined' is not assignable to type 'string[]'.
  Type 'undefined' is not assignable to type 'string[]'.ts(2322)
App.tsx(16, 3): The expected type comes from property 'observations' which is declared here on type 'IntrinsicAttributes & EventObj & { children?: ReactNode; }'
{game.note && game.observations && <GameCard 
  id={game.id}
  observations={game.observations}
  note={game.note}
/>}