2017-09-26 319 views
1

如何检查ticketId已经插入到数组中?React-native数组检查值是否存在

这是代码:

state = { myState: [], status: 0, limit: 5 }; 

    selected(ticketId) { 
    if (this.state.status < this.state.limit) { 
    this.state.myState.push({ id: ticketId }); //what ever i chose get inserted 
    this.state.status++; 
    this.setState({ status: this.state.status }); 
    //console.log('here', this.state.status); 
    } else { 
    console.log('3'); //check if condition meet 
    } 
} 

如何创建一个条件检查myState阵列如果ticketId已经插入并触发警报?

回答

1

当您存储为对象{id:value}时,最好使用“every”代替。

state = { myState: [], status: 0, limit: 5 }; 

selected(ticketId) { 
    if (this.state.status < this.state.limit) { 
     if(this.state.myState.every((item) => item.id !== ticketId)){ 
     this.state.myState.push({ id: ticketId }); //what ever i chose get inserted 
     this.state.status++; 
     this.setState({ status: this.state.status }); 
     //console.log('here', this.state.status); 
    } 
    } else { 
    console.log('3'); //check if condition meet 
    } 
} 
+0

谢谢你,我得到了正确的结果... –

2

你好,你可以使用loadashFind it Here对于这种问题它容易和非常好看! :)

举例:1

_.indexOf([1, 2, 1, 2], 2); 
// => 1 

或者您可以使用

举例:2

var users = [ 
    { 'user': 'barney', 'active': false }, 
    { 'user': 'fred', 'active': false }, 
    { 'user': 'pebbles', 'active': true } 
]; 

_.findIndex(users, function(o) { return o.user == 'barney'; }); 
// => 0 

// The `_.matches` iteratee shorthand. 
_.findIndex(users, { 'user': 'fred', 'active': false }); 
// => 1 

// The `_.matchesProperty` iteratee shorthand. 
_.findIndex(users, ['active', false]); 
// => 0 

// The `_.property` iteratee shorthand. 
_.findIndex(users, 'active'); 
// => 2 

在你的代码

_.findIndex(this.state.myState, { 'id': ticketId }); 
// It will return 0 if there is nothing 
// else will return no of index 
// where it ticketid is present 
// you can do alert on if its not 0