简体   繁体   中英

React Native Mapping Fail

React newbie here. I've got some React Code where I'm trying to loop through an array I provided in my .state and display the image. (using 'Image' and using a Card object from https://github.com/lhandel/react-native-card-stack-swiper to display the Image inside the Card object, which itself is nested inside the Object, but that's neither here nor there.)

export default class App extends Component<{}> {
  constructor(props) {
    super(props);
    this.state = {
      cards: [
        {itemname: 'Item 1',
          restoname: 'Resto 1',
          url: 'https://res.cloudinary.com/grubhub/image/upload/v1515191165/bkf4niv9okipbc8y6o8h.jpg',
          description: 'Desc 1'},
        {itemname: 'Item 2',
          restoname: 'Resto 2',
          url: 'https://res.cloudinary.com/grubhub/image/upload/v1514060352/twhriy3hvbzayktrjp91.jpg',
          description: 'Desc 2'}
      ]
    };
  }

render() {
    const contents = this.state.cards.map((item, index) => {
      return (
          <Card key={'Card_' + index}>
            <Image
                key={index}
                source={{uri: item.url}} />
          </Card>
      )
    });

return (
      <View style={{flex:1}}>

        <CardStack
          cards = {this.state.cards}
        >

         <View>
            {contents}
         </View>
        </CardStack>

Where I'm falling short, is the last part --- if I define contents as that mapping where it returns the <Card> and <Image> object inside of it, shouldn't that show up at the end when I'm calling {contents} inside the <CardStack> object? Nothing is showing up and there is no error message either.

Also, in addition to nothing showing up initially, if I swipe to go to the next card, I get an error of:

undefined is not an object (evaluating 'this.state.cards[sindex - 2].props`)

Assign the key to Card not Image, like this:

return (
   <Card key={index}>
       <Image
          source={{uri: item.url}} />
   </Card>
)

Key will be required for the wrapper element when creating elements dynamically, and in this case that element is Card.

Also, As per the DOC , you need to put the Card element directly inside CardStack, so remove the view and write it like this:

<CardStack> {contents} </CardStack>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM