reactjs - 如何将上下文一分为二
问题描述
我是 ReactJS 的新手,我来自后端(Ruby on Rails)背景。这是我的第一个 ReactApp
阅读文档,似乎我的LocationContextProvider有点大。我的目标是在每一个地方改变我都想:
- 更改正在播放的 Spotify 播放列表,这可以通过更改播放列表 ID 来完成
- 更改一个视频组件(尚未创建),我可以在侧边栏中显示“日本,千代田@夜”之类的文本。该字符串保存在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
解决方案
推荐阅读
- c++ - 无法创建 QFile(仅适用于 msvc2017 uwp)
- postgresql - 在 PostgreSQL/PostGIS 中的多边形交叉点内查找点太慢了
- android - 从 /Internal storage/DCIM/camera 发布图像时出现 403 错误
- javascript - 如何在按钮单击 vue.js 上导入其他组件
- android - 从 Firebase 投射数据时为空数据
- php - 在登录时将用户重定向到特定于其帐户的页面
- aspnetboilerplate - 无法在 aspnetboilerplate 中进行 CRUD
- mysql - Joining 2 or More Database with 1 column result
- c++ - 为什么这个矢量矢量的简单自定义比较器会产生崩溃?
- reactjs - 限制 S3 静态网站对 Cloudfront 的访问