[英]Ternary operator: Expected an assignment or function call and instead saw an expression
I am trying to map an array of typescript interface objects and print its values in a table.我正在尝试映射 typescript 接口对象数组并将其值打印在表中。 My array looks something like this:我的数组看起来像这样:
export interface data {
fields?: field[];
}
export interface field {
name: string;
description: string;
subfields: subfield[];
}
But I want to print only that field
which has field.name
equal to requiredName
但我只想打印field.name
等于requiredName
field
On usage of ternary operator to define condition I am getting the following error: Expected an assignment or function call and instead saw an expression
在使用三元运算符来定义条件时,我收到以下错误: Expected an assignment or function call and instead saw an expression
I would appreciate some help in defining conditional statements to map my object.我很感激在定义条件语句以映射我的对象方面的帮助。 I have used ternary operator before too but only for printing value in a table cell instead of dynamically creating one.我之前也使用过三元运算符,但仅用于在表格单元格中打印值,而不是动态创建一个。
Here´s my code so far:到目前为止,这是我的代码:
<Table>
<TableBody>
<TableRow >
<TableCell>
{props.fields.map((it) =>
{it.name===requiredName ? (
<Table>...</Table>
) : (
null
)}
)}
</TableCell>
</TableRow>
</TableBody>
</Table>
Thanks in advance.提前致谢。
You are missing the return statement in front of your ternary operator.您缺少三元运算符前面的 return 语句。
It should be:它应该是:
return it.name===requiredName ? (
<Table>...</Table>
) : (
null
)
You have curly brackets in your arrow function, and therefore your ternary operator is executed as statement in the function body, but not returned.您的箭头函数中有大括号,因此您的三元运算符在函数体中作为语句执行,但不返回。
This is what you currently have: (I just added the implicit return undefined
to the function body.)这就是您目前拥有的:(我只是在函数体中添加了return undefined
的隐式return undefined
值。)
<TableCell>
{props.fields.map((it) => {
it.name===requiredName ? (<Table>...</Table>) : (null)
return undefined
}
)}
</TableCell>
The result of you map function is therefore an array with only undefined
values in there.因此,您 map 函数的结果是一个数组,其中只有undefined
值。
You probably meant to do this (Note the absent curly brackets, which cause the arrow function to return the value of the ternary):您可能打算这样做(注意缺少大括号,它会导致箭头函数返回三元值):
<TableCell>
{props.fields.map((it) =>
it.name===requiredName ? (<Table>...</Table>) : (null)
)}
</TableCell>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.