简体   繁体   中英

react native map method not rendering

I'm doing a simple cryptocurrency app to display daily price and change. When rendering the view with 0 index with the info for the first coin the data is displayed, but when using the map method, nothing is displayed... here is the code for the view:

              <View style={styles.container}>
               <ScrollView contenContainerStyle={styles.coinList}>
                {this.state.coinList.map((coin, index) => {
                  alert (coin.symbol + ': ' + coin.price);
                  <CoinInfo
                    key={index}
                    symbol={coin.symbol}
                    name={coin.name}
                    price={coin.price}
                    change={coin.change}
                    active={false}
                    onPress={this.fonPress}
                  />;
                })}
              </ScrollView>
            <View/>

const styles = StyleSheet.create({
  container: {
    flex: 62,
    backgroundColor: '#40137A',
    alignItems: 'center',
    justifyContent: 'center',
  },
  loading: {
    justifyContent: 'center',
  },
  coinList: {
    flex: 1,
    flexDirection: 'row',
    flexWrap: 'wrap',
    justifyContent: 'space-around',
  }
});

I used an alert to see if the map is working and it alerts me 7 of the 8 coins i had in the array...

Thanx for your help

When using the Array.map method you should return the element to be added to the resulting array.

You see the alerts because the function is running, but since you are not returning the child elements the resulting array has nothing to be rendered.

Try this:

            {this.state.coinList.map((coin, index) => {
              alert (coin.symbol + ': ' + coin.price);
              return <CoinInfo
                key={index}
                symbol={coin.symbol}
                name={coin.name}
                price={coin.price}
                change={coin.change}
                active={false}
                onPress={this.fonPress}
              />;
            })}

I recommend you to take a look into the following link to understand Array.map better:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

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