首页 > 解决方案 > 如何将上下文一分为二

问题描述

我是 ReactJS 的新手,我来自后端(Ruby on Rails)背景。这是我的第一个 ReactApp

阅读文档,似乎我的LocationContextProvider有点大。我的目标是在每一个地方改变我都想:

  1. 更改正在播放的 Spotify 播放列表,这可以通过更改播放列表 ID 来完成
  2. 更改一个视频组件(尚未创建),我可以在侧边栏中显示“日本,千代田@夜”之类的文本。该字符串保存在videoPlaying中,并在每次视频更改时更改。当视频结束(我检查所选位置是否有另一个视频要显示,在此处完成)或用户选择新位置时,就会发生这种情况。

我想要实现的是将 LocationContext 的状态分离到不同的上下文中:

    this.state = {
      player: undefined,
      country: randomPlace.country,
      city: randomPlace.city,
      place: randomPlace.place, // This is street or the actual place
      videosPlayed: [], // Here we will push all the youtubeIDs played, we will empty it when the location is changed
      videosAllowedToPlay: videosAllowedToPlay,
      videoPlaying: undefined,
      setCountry: this.setCountry,
      setCity: this.setCity,
      setPlace: this.setPlace,
      setVideoPlaying: this.setVideoPlaying
    };

例如有两个新的上下文:

背景一:

    this.state = {
      player: undefined,
      country: randomPlace.country,
      city: randomPlace.city,
      place: randomPlace.place, // This is street or the actual place
      videosPlayed: [], // Here we will push all the youtubeIDs played, we will empty it when the location is changed
      videosAllowedToPlay: videosAllowedToPlay,
      setCountry: this.setCountry,
      setCity: this.setCity,
      setPlace: this.setPlace,
    };

上下文 2:

    this.state = {
      videoPlaying: undefined,
      setVideoPlaying: this.setVideoPlaying
    };

因此,基于 Context1 的状态,我可以更改 Context2 的videoPlaying属性(不知道如何或在哪里这样做)

然后使用 Context2 而不是使用 LocationContext 并在每次状态属性更改时重新渲染整个组件,因为我真的只对 videoPlaying 属性感兴趣,但我需要保存 Context1 属性的状态。

提前致谢!

源代码:https ://github.com/MatayoshiMariano/feeltheworld/tree/stackoverflow-question

标签: reactjsreact-context

解决方案


推荐阅读