Morton
Morton

Reputation: 5782

How to render FlatList with two array?

I want to render a FlatList with two arrays that are name and photo. I hope my FlatList each of item include name and photo.

But i don't know how to merge them into my FlatList data.

console.log my movieActorCn array like this:

["A", "B", "C", "D", "E"]

movieActorPhoto array like this:

["https://movies.yahoo.com.tw/x/r/w290/i/o/productio…names/June2017/DL56QvvLdISH9D3U1dOR-6144x4096.jpg", "/build/images/noavatar.jpg", "https://movies.yahoo.com.tw/x/r/h290/i/o/production/names/April2018/dPWzXuXupOAHs2ZW2jdk-408x590.jpg", "https://movies.yahoo.com.tw/x/r/w290/i/o/production/names/April2018/123akbim6D7wsxqnoJJ0-400x266.jpg", "https://movies.yahoo.com.tw/x/r/w290/i/o/productio…names/June2017/DL56QvvLdISH9D3U1dOR-6144x4096.jpg"]

I try to merge them by using Array.prototype.push.apply(movieActorCn, movieActorPhoto); I cosole.log(movieActorCn); and find the array just cahnge from 5 to 10. It can't be used if i want to render each item include one name and one photo.

I hope my renderActor function can render name and photo. Like render with <Image /> and <Text /> How to do it ?

Any help would be apprecriated. Thanks in advance.

render() { const { movieActorCn, movieActorPhoto } = this.state.movies;

//It just caange from 5 to 10
Array.prototype.push.apply(movieActorCn, movieActorPhoto);
console.log(movieActorCn);

return (
        <FlatList
          data={movieActorPhoto}
          renderItem={this.renderActor}
          horizontal={true}
          keyExtractor={(item, index) => index.toString()}  
        />

);

}

renderActor({ item }) {
    console.log('renderActor');
    console.log(item);
    return (
      <View
        style={{     
          alignSelf: 'stretch',
          backgroundColor: '#fff',
          borderRadius: 5,
          borderWidth: 1,
          borderColor: '#fff',
          marginLeft: 10,
          marginRight: 10 
        }}
      >
      <Image 
        source={{uri: item }} 
        style={{height: 120, width: equalWidth, resizeMode: 'stretch', flex: 1}}
      />
      </View>
    );

Upvotes: 1

Views: 3627

Answers (2)

Bored
Bored

Reputation: 499

Just push your arrays in one array:

   let a=[];
   let b=[];
   let c=[];

   c.push(...a);
   c.push(...b);

Upvotes: 0

Roy Wang
Roy Wang

Reputation: 11270

Try this:

<FlatList
  data={movieActorPhoto}
  extraData={movieActorCn /* so that list is re-rendered when `movieActorCn` changes */}
  keyExtractor={item => item}
  renderItem={({ item, index }) => (
    <View>
      <Image source={{ uri: item }} />
      <Text>{movieActorCn[index]}</Text>
    </View>
  )}
/>

It might be better to change your data structure to

[ { name: 'A', photo: 'https://...' } ]

Upvotes: 3

Related Questions