如何将上下文一分为二

时间:2020-07-20 13:17:37

标签: reactjs react-context

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

阅读文档,似乎我的LocationContextProvider有点大。我的目标是在每次place更改中都希望:

  1. 更改正在播放的Spotify播放列表,这可以通过更改播放列表ID来实现
  2. 更改视频组件(尚未创建),在其中可以在侧边栏中显示诸如“ Japan,Chiyoda @ Night”的文本。该字符串将保存在videoPlaying中,并在每次视频更改时进行更改。当视频结束时(我检查所选位置是否还有其他视频要显示,here完成),或者用户选择了新位置,就会发生这种情况。

我想要实现的是将LocationContext的状态分为不同的Context:

    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
    };

例如具有两个新的上下文:

上下文1:

    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并重新渲染整个组件,bc我真的只对videoPlaying属性感兴趣,但是我需要保存Context1属性的状态。 / p>

谢谢!

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

0 个答案:

没有答案