地图内的三元运算符 [英] ternary operator inside map

查看:62
本文介绍了地图内的三元运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm working on a webapp where the user views a list of items and can mark certain items as favourites. The favourites are provided as an array of ID's with a prop (this.props.favourites). To prevent duplicate entries I want to replace the 'add to favourites' button with a 'delete from favourites' button if the item.id is already in the this.props.favourites array.

但是,我编写的三元If语句因语法错误而崩溃.但是我以为我遵循了官方示例( https://reactjs.org/docs/conditional-rendering .html ).

However, the ternary If statement I've made crashes on a syntax error. Yet I thought I followed the official example (https://reactjs.org/docs/conditional-rendering.html) pretty closely.

这是我使用的代码:

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>
       );
   }
}

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

Does anyone have an idea what I am doing wrong?

推荐答案

尝试以下类似操作

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

这篇关于地图内的三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆