Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-native-video not change video when change source

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?

like image 394
Trí Lâm Avatar asked Mar 03 '23 18:03

Trí Lâm


1 Answers

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.

like image 100
Jaydeep Galani Avatar answered Mar 05 '23 15:03

Jaydeep Galani