2017-10-16 76 views
0

我尝试使用组件的循环数,但似乎无效。我setStatetotalitem至5,并且输出部件只有1.React Native - For Loop组件

_renderSomeItems(){ 
    for(var i = 0; i < this.state.totalitem; i++){ 
    return(
     <SpecialItem key={i} /> 
    ); 
    }  
} 
+1

的可能重复[返回是否停止循环?(https://stackoverflow.com/questions/11714503/does-return-stop-a-loop) – bennygenel

回答

1

return内部的for循环将结束循环。你应该使用Array.prototype.map()。不要忘了mapreturn结果。

_renderSomeItems(){ 
    // considering this.state.totalitem is to be an array 
    return this.state.totalitem.map((item, index) => { 
    return(
     <SpecialItem key={index} /> 
    ); 
    }  
} 

// or 

_renderSomeItems(){ 
    const results = []; 
    for(var i = 0; i < this.state.totalitem; i++){ 
    results.push(<SpecialItem key={i} />); 
    } 
    return results; 
} 
+0

感谢答复,'this.state。 totalitem'只是一个数字。我在我的问题中提到,我将它设置为'5' –

+1

然后第二个版本对你来说是更好的选择。这就是为什么我加了第一个评论 – bennygenel

+0

感谢它的工作! –

0

使用lodash

import _ from 'lodash' 

_renderSomeItems(){ 
    return _.range(this.state.totalitem).map(item, index) => (
    <SpecialItem key={i} /> 
); 
}