使用foreach在数组中选择正确的索引

时间:2018-07-28 17:34:12

标签: javascript reactjs react-native

我这个问题有点麻烦了。我使用forEach遍历数组,当我单击组件时,我希望使用相应的索引呈现正确的页面。现在,我的问题是我遍历了数组,但是我无法返回正确的索引,只能返回数组中的第一个索引。我希望startPage组件上的Pages道具能够通过我的newNum变量呈现为正确的索引。

const itemId = this.props.navigation.getParam('pk');

let newArray = this.props.moment.filter(item => {
  return item.trip == itemId
});
console.log('getting moment fromt trip')
let num = Object.keys(this.props.trip[0].moments)
let newNum = num.forEach((number, index) => {
  console.log(number)
  return number
})

return (
  // <View style={{flex:1, backgroundColor: '#F0F5F7'}} {...this.panResponder.panHandlers}>
  <View style={{flex:1, backgroundColor: '#F0F5F7'}}>
  <HeaderMomentComponent navigation={this.props.navigation} />
  <Pages indicatorColor="salmon" startPage={newNum}>
    {newArray.map((item, index) => {
      console.log('this is the index')
      console.log(index)
      return(
        <MomentContent
          name={item.name}
          place={item.place}
          description={item.description}
          tags={item.tags}
          key={index}
        />
      )
    })}
  </Pages>
</View>
);

1 个答案:

答案 0 :(得分:1)

根据MDN documentation(Mozilla开发人员网络),forEach的返回值为undefined

使用Array#map返回一个newNum值。

let newNum = num.map((number, index) => {
  // Some logic to get a new number...
  return number
})