React - 如何回到默认状态?

React - How to go back to default state?

我正在播放 Youtube 视频。一旦输入内容,API 服务器将回复 URL,在与 Youtube 相同的播放器中播放。 API 的视频结束后如何返回 YT 视频?

播放器视频代码 (Typescript) 如下所示,它由 videoUrlProp 提供,该状态处理来自父组件的 URL 响应。

const Player: React.FC<IProps> = ({
  onProgress,
  videoUrlProp,
}:
IProps) => {

// Don't mind this segment.
  const { playerRef, isPlaying } = useStore(
    (state) => ({ playerRef: state.playerRef, isPlaying: state.isPlaying }),
    shallow
  );

  // We check if the source is the original. This is used to resize the player.
  const isOriginalVideo = videoUrlProp.includes("youtube");

  return (
    <div className="player">
      <ReactPlayer
        url={videoUrlProp}
        controls={true}
        onProgress={onProgress}
        width={isOriginalVideo ? "100%" : "70%"}
        height={isOriginalVideo ? "100%" : "100%"}
        className="react-player"
        ref={playerRef}
        playing={isPlaying}
      />
    </div>
  );
};

export default Player;

我正在为播放器使用 react-player;这就是在父组件中声明状态的方式:

const [videoUrl, setVideoUrl] = useState(
    "https://www.youtube.com/watch?v=something"
  );

欢迎任何帮助。谢谢!

*编辑:我对在 Whosebug 上提问还是有点陌生​​,如果我遗漏了一些数据或者我是否应该以不同的方式写下来,请告诉我!泰! :)

状态没有“重置”功能。但是很容易模拟出来。

如果您设置您的状态并公开 default/initial 值,那么您将得到如下内容:

const defaultVideoUrl = "https://www.youtube.com/watch?v=something"

然后在您的组件中的某处声明状态:

const [videoUrl, setVideoUrl] = useState(defaultVideoUrl);

然后您在视频结束时设置回默认值,according to the docs 是通过使用 onEnded 属性:

<ReactPlayer
  ...otherProps
  onEnded={() => setVideoUrl(defaultVideoUrl)}
/>

您可以将函数道具传递给您的子组件,在视频结束时使用 useEffect 调用它以触发父组件中的重置。

useEffect(()=> { 
   if (isVideoFinished) props.reset(true)
}, [isVideoFinished])

并在你的父组件中简单地做

const reset = (shouldReset) => {
  if (shouldReset) {
    setVideoUrl('reset to whatever you want')
  }
}