gpt4 book ai didi

javascript - map 内的三元运算符

转载 作者:行者123 更新时间:2023-12-03 13:58:03 24 4
gpt4 key购买 nike

我正在开发一个网络应用程序,用户可以在其中查看项目列表,并可以将某些项目标记为收藏夹。收藏夹以带有 prop (this.props.favourites) 的 ID 数组的形式提供。为了防止重复条目,如果 item.id 已经在 this.props.favourites 数组中,我想用“从收藏夹中删除”按钮替换“添加到收藏夹”按钮。

但是,我所做的三元 If 语句因语法错误而崩溃。但我认为我非常严格地遵循了官方示例( https://reactjs.org/docs/conditional-rendering.html )。

这是我使用的代码:

render() { 

const items = this.state.items.map((item, index) => (
<p key={index}>
{item.name}
</p>

{(this.props.favourites.include(item) ? (
<button>add fvourites</button>
) : (
<button>delete</button>
)}

));
return (
<div>
<button onClick={this.LoadApi}>Show fetch Items</button>
<div>{items}</div>
</div>
);
}
}

有人知道我做错了什么吗?

最佳答案

问题:

1- 您在 map 回调方法中返回 2 个元素,这是不正确的,因此将它们包装在 div 中。

2- 这里有一个额外的 (:{(this.props.favourites.include(item)

3-使用includes而不是include

解决方案:

const items = this.state.items.map((item, index) => (
<div key={index}>
<p>
{item.name}
</p>

{this.props.favourites.includes(item) ? (
<button>add fvourites</button>
) : (
<button>delete</button>
)}
</div>
))

关于javascript - map 内的三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48599660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com