6

I use react-native-video to render a video player for my app.

I try to change the source of the video. This is my code run well.

<Video
  source={{uri: _getVideo().video_url}}
  style={Styles.backgroundVideo}
  autoplay={true}
  controls={false}
  disableFocus={true}
  resizeMode="cover"
/>;

But I change 'controls={true}'. It don't render new video, just render audio. And still show old video.

_getVideo().video_url

This function just return source video. I'm sure element also changes source but not re-render new video.

Is there any solution to resolve it?

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
Trí Lâm
  • 75
  • 3
  • 9

1 Answers1

10

You are doing it the wrong way, though it works.

But let me tell you what's happening here,

source={{uri: _getVideo().video_url}}

this line executes every time the render method is executed, and the render method is called after setState, props changes, and other events.

So your _getVideo() method will be called any number of times though it is not required.

Hence I suggest you initialize one state variable for URL. call your _getVideo() somewhere you want. maybe on componentDidMount for first run and afterward button click or anything else you want but set this URL into that state with setState in _getVideo method.

so desired thing will be like this,

<Video
  key={this.state.videoComponentKey}
  source={{uri: this.state.video_url}}
  style={Styles.backgroundVideo}
  autoplay={true}
  controls={false}
  disableFocus={true}
  resizeMode="cover"
/>;

Now if you have noticed I have added one more prop key, this will solve your old video problem. whenever URL is changed change something in the key. so I have taken one state and passed it to this prop. now you can initialize it with 0 and next time just increment it using setState.

AmerllicA
  • 29,059
  • 15
  • 130
  • 154
Jaydeep Galani
  • 4,842
  • 3
  • 27
  • 47