React-native-video not change video when change source
Asked Answered
E

1

8

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?

Emblements answered 3/3, 2020 at 4:56 Comment(0)
T
12

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.

Turbit answered 3/3, 2020 at 6:13 Comment(1)
That's working fine must have unique key ("videoComponentKey").Outrange

© 2022 - 2024 — McMap. All rights reserved.