2017-09-26 22 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