如何破解.map功能

时间:2018-01-14 08:59:07

标签: reactjs react-native

如何打破.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>

4 个答案:

答案 0 :(得分:6)

在映射之前使用Array.slice

peopleGroup
.slice(0, 5) // creates a copy of original, 5 items long
.map(...) // subsequent operations work on the copy

多田!

答案 1 :(得分:2)

而不是使用.slice.map来创建另一个循环 您可以使用.reduce,这样您就可以通过一个循环来实现逻辑(更好的性能) 区别在于.map必须返回相同长度的数组,其中.reduce可以实际返回任何内容。

  data.reduce((result, current, i) => {
    if (i < 5) {
      result.push(<div>{current}</div>);
    }
    return result;
  }, [])

运行示例:

&#13;
&#13;
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'));
&#13;
<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>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

  

如何打破.map功能?

不可能,我们不能打破#array.map,它会为数组的每个元素运行。

要解决您的问题,您可以先使用slice然后映射slice前5个数组元素,然后在其上运行地图。

像这样:

peopleGroup.slice(0,5).map((people, i) => {
    return (...)
}

答案 3 :(得分:0)

抛出新的错误(e);将其添加到try catch中以防止崩溃。