html - 如何将 const 传递给多个组件/拆分 React-Redux-Router 文件
问题描述
我正在使用其 API 创建一个 Spotify 应用程序。我想要 4 个视图(例如“/”、“nowPlaying”、“favouriteArtists”、“favouriteSongs”)。
我需要setAccessToken
使用getMyCurrentPlaybackState()
每个新页面中的功能,对吗?如果我需要if(params.access_token){spotifyWebApi.setAccessToken(params.access_token)}
在每个将使用getMyCurrentPlaybackState()
. 我正在考虑创建一个 Spotify.jsx 容器来处理 Spotify 对象的存储(在令牌和每个使用 Spotify 函数的容器中使用)。但是对于这个 Spotify.jsx,我既不知道它是否是一个好方法,也不知道如何将connect
它需要的spotifyWebApi
const 用于每个容器文件和令牌文件。
为了更好地理解我的想法:我将创建一个 Token.jsxgetHashParams()
和一个 Playing.jsx getNowPlaying()
。每个人都需要spotifyWebApi
const。
import React, { Component } from 'react';
import Spotify from 'spotify-web-api-js';
const spotifyWebApi = new Spotify();
class App extends Component {
constructor(){
super();
const params = this.getHashParams();
this.state = {
loggedIn: params.access_token ? true : false,
nowPlaying: {
name: 'Not Checked',
image: ''
}
}
if (params.access_token){
spotifyWebApi.setAccessToken(params.access_token)
}
}
getHashParams() {
var hashParams = {};
var e, r = /([^&;=]+)=?([^&;]*)/g,
q = window.location.hash.substring(1);
while ( e = r.exec(q)) {
hashParams[e[1]] = decodeURIComponent(e[2]);
}
return hashParams;
}
getNowPlaying(){
spotifyWebApi.getMyCurrentPlaybackState()
.then((response) => {
this.setState({
nowPlaying: {
name: response.item.name,
image: response.item.album.images[0].url
}
})
})
}
}
解决方案
您的标题提到了 Redux,但我没有看到您的代码使用它。使用 Redux,您可以获取 access_token,然后将其存储在 state 中。这将允许您在任何 Redux 连接的组件中使用它。
此外,使用 Redux,您可以使用Redux Thunk(或类似的)中间件,它允许您使用 Redux 操作来调用 API。因此,您只需将不同的 API 调用编写为 Redux 操作,这将允许您从任何组件调用它们,并将结果添加到您的 Redux 存储(同样,可以在任何与 Redux 连接的组件中使用)。
因此,例如,您的getNowPlaying()
函数可能是一个看起来像这样的动作:
function getNowPlaying() {
return function (dispatch, getState) {
// get the token and init the api
const access_token = getState().spotify.access_token
spotifyWebApi.setAccessToken(access_token)
return spotifyWebApi.getMyCurrentPlaybackState().then((response) => {
dispatch({
type: 'SET_NOW_PLAYING',
name: response.item.name,
image: response.item.album.images[0].url
})
})
}
}
注意:你需要为“spotify”配置Redux reducer(或者你想构建你的 store)来存储你需要的数据。
因此,您可以从任何组件调用 getNowPlaying()。它将结果存储在 redux 存储中,您也可以从任何连接的组件中使用它。并且您可以在操作中需要时使用从商店获取 access_token 的相同技术。
或者,如果您不想使用 Redux,您可以使用React 的 Context特性为所有子组件提供上下文值。您可以使用设置中每个组件所需的令牌来执行此操作。但在我看来,Redux 是你更好的选择。