在本机中终止地图循环

时间:2017-01-24 21:52:33

标签: react-native

我试图突破一个循环,一旦我找到了我正在寻找的东西,在这种情况下是一个引用。

我知道使用像Java这样的东西实际上是可能的,但事实证明它比我在RN中想象的要困难。当我使用JS中断时,它只是说它的语法错误,RN中有任何break语句吗?

enter image description here

quotes.quotesArray.map((quote, i) => {
    if(!quote.isRead){
        return <Text key={i} style={styles.container, styles.quote}>{quotes.quotesArray[i].quotation}</Text>;                    
        break;
    } else {
       return 
    }
})

3 个答案:

答案 0 :(得分:2)

没有办法过早地打破Array.prototype.map。看起来您想渲染与!quote.isRead谓词匹配的第一个元素。如果是这种情况,您可以使用Array.prototype.find查找第一个未读报价,然后在其存在时进行呈现。

var unreadQuote = quotes.quotesArray.find(quote => !quote.isRead)
render() {
  return (
    unreadQuote && 
    <Text style={styles.container, styles.quote}>{unreadQuote.quotation}</Text>;
  )
}

答案 1 :(得分:1)

我会使用filter和map来执行此操作,并将组件的渲染移动到函数:

int leggiSequenza(char *nomeFile, int **seq);
//                                ^^^^^^^^^

答案 2 :(得分:0)

问题是你返回开始下一个循环所以它永远不会到达break,这是另一种你可以设置它的方法。编辑for for循环从forEach for break有效。

const quote = [];
for ( let i = 0; i < quotes.quotesArray.length; i++) {
  if (!quote.isRead[i]) {
    quote.push(<Text key={i} style={styles.container, styles.quote}>{quotes.quotesArray[i]}</Text>);
    break;
  }
}

您还可以使用lodash的.find()方法过滤数组并返回在回调中返回true的第一个元素,并将该数据用于文本元素。