无法根据不正确的书面 if/else 语句返回图标



我有这样的对象数组:

{
"comment_description": "hello, this is false answer",
"right_answered_by_post_author": false
},
{
"comment_description": "hello, this is true answer",
"right_answered_by_post_author": true
},
{
"comment_description": "hello, this is false answer",
"right_answered_by_post_author": false
}
] 

我想制作答案徽章(主要看起来像堆栈溢出答案徽章(,在组件中呈现相关图标。(

我使用 Fontawesome 进行反应,如果至少有一个对象包含:"right_answered_by_post_author":true

当有一些答案但甚至没有一个"right_answered_by_post_author"时,我想渲染未经检查的绿色方块:真(所有答案都是假的(

如果没有任何答案,我希望渲染未经检查的本机非样式图标。(如果数组中没有任何对象(

我尝试.map"答案"对象的数组并检查是否有"真"答案渲染"faCheckSquare"图标,如果没有真答案但所有错误答案渲染绿色faSquare图标,如果数组不包含任何答案对象Redner本机faSquare图标。

但是,在相关组件中呈现的图标数量与数组中的答案对象数量相同。 示例:如果数组中有 6 个答案,则组件呈现 6 个图标。(我希望你明白我的意思(

有人可以帮助我编写正确的迭代代码来检查数组的任何对象中是否有"truish"答案,或者没有或数组为空?


编辑: 让我编辑我的问题并添加一些代码 我有假后端 (JSON(,我像那样映射它

let posts = this.state.posts.map(singlePost => {
return (
<PresentationalComponent 
key={it doesn't matter}
text={singlePost.comment_description}
answerCheck={singlePost.post_comments.map(check => {
if (firstCheck.right_answered_by_post_author === true) {
return (
<FontAwesomeIcon style={{'color': 'green'}} icon= 
{faCheckSquare} />
)
}else {
return <FontAwesomeIcon style={{'color': 'green'}} icon= 
{faSquare} />
}
})}
/>
)
post.comments   //is the thing which contains the array what I showed you in the start part of the post.

我知道这是我想做的事情的错误代码。它也不包含数组为空时要执行的操作。 对不起,我的问题表述很糟糕。 提前感谢您的帮助。

您可以遍历数组并检查是否存在真实值,如下所示:

let array = [
{
"comment_description": "hello, this is false answer",
"right_answered_by_post_author": false
},
{
"comment_description": "hello, this is true answer",
"right_answered_by_post_author": true
},
{
"comment_description": "hello, this is false answer",
"right_answered_by_post_author": false
}
]

const check = () => {
let reducedArray = array.map(obj => obj.right_answered_by_post_author)
return reducedArray.includes(true) ? true : false
}
这将返回 true 或 false,具体取决于数组中是否存在 true 值。然后,您可以将图标呈现绑定到它。

由于您描述了但没有显示任何代码,我正在猜测您的变量是什么样的。这是我的方法:

const  answersArray = [...objects]
if (answersArray.length){
answersArray.filter((item) => item['right_answered_by_post_author']).length ? <CheckedGreenSquare/> : <UncheckedGreenSquare/>
} else <UncheckedNativeSquare/>

希望对你有帮助

最新更新