簡體   English   中英

React-Native數組檢查值是否存在

[英]React-native array check if value exist

如何檢查ticketId已插入數組?

這是代碼:

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

如果ticketId已插入並觸發警報,如何創建條件檢查myState數組?

您好,您可以使用loadash 在這里查找此類問題,它看起來非常好看! :)

范例: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

當您存儲為對象{id:value}時,最好改用“每一個”。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM