组件回调执行旧状态

时间:2020-06-22 06:05:14

标签: javascript reactjs react-native

有人可以向我解释为什么此Video组件返回旧功能状态吗?另外,我该如何修复它以使其正常运行?!

简而言之-我们有一个带数字的州。当视频以状态结束时,我们传递一个回调。我们通过增加状态来更新状态。视频结束时,输出为0。

import React from 'react';
import {

  View,
  Text,
  Button,
} from 'react-native';
import VideoPlayer from 'react-native-video-controls';
import Video from 'react-native-video';

const App: () => React$Node = () => {
  const [numb, setNumb] = React.useState(0)

  const updateName = ()=>{
    setNumb(numb+1); 
  } 

  const markCompleted = () => {
    console.log(this); // this out puts 0, rather than the real increment. 
  }

  const u = 'https://109vod-adaptive.akamaized.net/exp=1592768084~acl=%2F461a5eea-6bfd-4205-af03-fcf9b49aca44%2F%2A~hmac=fe971a0d1c64348aaf30655e2ce2c903aae53c9090b966f2e00bd1a1d680bf68/461a5eea-6bfd-4205-af03-fcf9b49aca44/sep/video/292418df,3387147e,464ad6f7,48786f72,621eeb8d,76569e72,91b1e89d/master.m3u8';
  //'https://96vod-adaptive.akamaized.net/exp=1592763689~acl=%2F300003695%2F%2A~hmac=5690283c331e7d782b59c9fd45500dd2241f3161372f5aff610d2fb5379c3880/300003695/sep/video/1145555175,1145555174/master.m3u8';

  return (
    <View style={{flex:1, paddingTop: 100}}>
      <Text>{numb}</Text>
      <Button title="update" onPress={updateName} />
      <VideoPlayer
              source={{ uri: u  }}
              onEnd={markCompleted}
            ></VideoPlayer>
{/* <Video source={{uri: u }}  style={{width: 400, height: 400}}  onEnd={markCompleted} controls={true}/> */}
    </View>
  );
};

export default App;

如果我们使用React社区的常规视频播放器,则不会出现此类问题。

这是错误的视频播放器代码: https://github.com/itsnubix/react-native-video-controls/blob/master/VideoPlayer.js

这可能是罪魁祸首,但我不知道为什么:

this.events = {
   ...
   onEnd: this.props.onEnd || this._onEnd.bind(this),
   ...
};

感觉就像是复制了传递的函数,而不是使用引用。我该如何避免呢?

如果我更改该文件以将this.props.onEnd传递到VideoPlayer,它将正常工作。但是,如果通过了this.events.onEnd,它将使用最初存储的功能,并且会在通过时返回其参数。

真的可以提供解决方案和解释。谢谢!

来自Package.json的依赖项:

  "dependencies": {
    "react": "16.11.0",
    "react-native": "0.62.2",
    "react-native-video": "^4.4.5",
    "react-native-video-controls": "^2.6.0",
    "react-native-webview": "^10.2.3"
  },

0 个答案:

没有答案