简体   繁体   English

如何防止map()在react-native中一次渲染整个数组

[英]How to prevent map() from render whole array at once in react-native

Hi folks I'm using viewPager and inside viewpager I'm rendering the array of videos using map.大家好,我正在使用viewPager而在 viewpager 中,我正在使用地图渲染视频数组。 But I wan to show 1 video at one time as I'm giving height and width 100%.但是我想一次显示 1 个视频,因为我将高度和宽度设置为 100%。 But when I run the app the all videos start playing.Only one show on the screen and the sound of other videos playing too.但是当我运行该应用程序时,所有视频都开始播放。屏幕上只显示一个,其他视频的声音也在播放。 I want to prevent that.我想阻止这种情况。 How can I do that?我怎样才能做到这一点?

Here is my code.这是我的代码。

<ViewPager
        onPageSelected={(e) => {
          setActive(e.nativeEvent.position);
          // setPaused(true);
        }}
        orientation="vertical"
        style={{height: '100%'}}
        initialPage={0}>
        {vids.map((item,index) => {
          return (
            <View key={index}>
              <Video
               paused={item.paused}
                source={{uri: item.vid}}
                style={styles.mediaPlayer}
                volume={0.5}
                resizeMode="cover"
                repeat={true}
                
                onReadyForDisplay={() => SetVideoLoad(false)}
              /></ViewPager

The problem is the way you are using the map.问题在于您使用地图的方式。

vids.map((item,index) => {
      return (
        <View key={index}>
                    ....
         <View /> ) ..

will iterate through all the elements of the map and display their respective videos.将遍历地图的所有元素并显示它们各自的视频。 What you need is to create something like a state variable that will have the info for just one video from the map and just pass its info to the < Video /> component.您需要的是创建类似状态变量的内容,该变量将仅包含地图中一个视频的信息,并将其信息传递给 < Video /> 组件。 You will need to have other react components like a button to move to another element of the map to play another video.您将需要其他反应组件,例如按钮以移动到地图的另一个元素以播放另一个视频。 Every time you click in this "button" you will execute some code to get another element of the map and play the respective video.每次单击此“按钮”时,您都会执行一些代码以获取地图的另一个元素并播放相应的视频。

You can simply do this in the following way您可以通过以下方式简单地执行此操作

const [pause,setPause]= useState(true)

               <Video
               paused={pause}
                source={{uri: item.vid}}
                style={styles.mediaPlayer}
                volume={0.5}
                resizeMode="cover"
                repeat={true}
                onTouchStart={()=>{setPause(!pause)} //<=== Add this line
                onReadyForDisplay={() => SetVideoLoad(false)}
              />

I hope this will help you.Happy Coding :D我希望这会帮助你。快乐编码:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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