如何破坏.map函数?下面附有代码示例。我想打破看一旦索引达到5,因为我只想渲染5阿凡达到屏幕。
<View style={{ flexDirection: 'row', marginTop: 20, marginLeft: 30 }}>
{
peopleGroup.map((people, i) => {
if(i<5) {
return (
<Avatar
key={people.id}
width={30}
position='absolute'
containerStyle={{ transform: [{translate: [-28 + (28 * i), 0, 1 - (i * 0.1)]}] }}
small
rounded
source={{uri: people.image}}
activeOpacity={0.7}
/>
)
}else if(i===5) {
return (
<View key={i} style={{ transform: [{translate: [(25 * i), 9, 0]}] }}>
<Text>{peopleGroup.length}</Text>
</View>
)
}
}
)
}
</View>发布于 2018-01-14 09:02:19
在地图绘制之前使用Array.slice。
peopleGroup
.slice(0, 5) // creates a copy of original, 5 items long
.map(...) // subsequent operations work on the copy塔达!
发布于 2018-01-14 09:06:47
如何破坏.map函数?
不可能,我们不能破坏#array.map,它将为数组的每个元素运行。
为了解决您的问题,您可以先使用切片,然后使用map,然后使用切片数组的前5个元素,然后运行映射。
如下所示:
peopleGroup.slice(0,5).map((people, i) => {
return (...)
}发布于 2018-01-14 09:22:59
您可以使用.reduce,这样您就可以用一个循环(更好的性能)来执行逻辑。
不同的是,.map必须返回相同长度的数组,其中.reduce实际上可以返回任何内容。
data.reduce((result, current, i) => {
if (i < 5) {
result.push(<div>{current}</div>);
}
return result;
}, [])运行示例:
const data = [1, 2, 3, 4, 5, 6, 7];
const App = () => (
<div>
{data.reduce((result, current, i) => {
if (i < 5) {
result.push(<div>{current}</div>);
}
return result;
}, [])}
</div>
);
ReactDOM.render(<App />, document.getElementById('root'));<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
https://stackoverflow.com/questions/48248067
复制相似问题